题目链接:点击打开链接
n=0时要输出1,否则会wa
代码:
#include<iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cmath>
#include <queue>
#include <map>
using namespace std;
const int maxn = 200000;
int pre[maxn+5],cnt[maxn+5];
int Find(int x){
int r=x;
while(pre[r]!=r) r = pre[r];
int i=x,j;
while(pre[i]!=r){
j = pre[i];
pre[i] = r;
cnt[r] += cnt[i];
cnt[i] = 0;
i = j;
}
return r;
}
map<int,int> mp;
int main(){
int n;
while(scanf("%d",&n)!=EOF){
if(n == 0) {printf("1\n");continue;}
mp.clear();
int k = 1;
for(int i=1; i<=n*2; i++){
pre[i] = i;
cnt[i] = 1;
}
int x,y;
for(int i=1; i<=n; i++){
scanf("%d%d",&x,&y);
if(mp.count(x) == 0){
mp[x] = k++;
}
if(mp.count(y) == 0){
mp[y] = k++;
}
x = mp[x];
y = mp[y];
int fx = Find(x), fy = Find(y);
if(fx != fy){
pre[fx] = fy;
cnt[fy] += cnt[fx];
cnt[fx] = 0;
}
}
int ans = 0;
for(int i=1; i<k; i++){
ans = max(ans,cnt[i]);
}
printf("%d\n",ans);
}
return 0;
}