1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| #include<bits/stdc++.h>
using namespace std;
template<typename T>void read(T&x){x=0;int fl=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-') fl=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}x*=fl;} template<typename T,typename...Args>inline void read(T&t,Args&...args){read(t);read(args...);}
typedef long long LL; typedef vector<int> vi; typedef pair<int, int> pii; #define mp(x, y) make_pair(x, y) #define pb(x) emplace_back(x)
const int N = 200005;
int n, a[N], b[N], t[N];
int fa[N], sz[N]; bool loop[N]; int findfa(int x){ return x == fa[x] ? x : fa[x] = findfa(fa[x]); } void unionn(int x, int y){ x = findfa(x), y = findfa(y); fa[y] = x; loop[x] |= loop[y]; sz[x] += sz[y]; }
int main(){ int CASES = 0; int T; for(read(T); T; T--){ read(n); for(int i = 1; i <= (n << 1); i++) fa[i] = i, loop[i] = false, sz[i] = 1; t[0] = 0; for(int i = 1; i <= n; i++){ read(a[i], b[i]); t[++t[0]] = a[i], t[++t[0]] = b[i]; } sort(t+1, t+t[0]+1); t[0] = unique(t+1, t+t[0]+1) - (t+1); for(int i = 1; i <= n; i++){ a[i] = lower_bound(t+1, t+t[0]+1, a[i]) - t; b[i] = lower_bound(t+1, t+t[0]+1, b[i]) - t; if(findfa(a[i]) == findfa(b[i])) loop[findfa(a[i])] = true; else unionn(a[i], b[i]); } int ans = 0; for(int i = 1; i <= t[0]; i++){ if(fa[i] != i) continue; ans += loop[i] ? sz[i] : sz[i] - 1; } printf("Case #%d: %d\n", ++CASES, ans); } return 0; }
|