题目链接
为什么能这么埋坑???我还以为我错了,结果找不到BUG,后来一看Discuss,发现竟是这种问题。。。
一般情况,我们都是while(T--)就行,但这道题可真就不一样了,它还需要while(scanf("%d", &T)!=EOF)!!!
其余的,就是简单的带权并查集了。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN=100005;
int N, diff, num[maxN<<1], root[maxN<<1], cnt;
struct node
{
string x, y;
node(string a="", string b=""):x(a), y(b) {}
}ss[maxN];
set<string> st;
set<string>::iterator it;
map<string, int> mp;
int fid(int x) { return x==root[x]?x:(root[x]=fid(root[x])); }
void init()
{
st.clear(); diff=0;
for(int i=1; i<=2*N; i++) { root[i]=i; num[i]=1; }
}
int main()
{
int T;
while(scanf("%d", &T)!=EOF)
{
while(T--)
{
scanf("%d", &N);
init();
for(int i=1; i<=N; i++)
{
cin>>ss[i].x>>ss[i].y;
st.insert(ss[i].x);
st.insert(ss[i].y);
}
diff=(int)st.size();
int i=0;
for(it=st.begin(); it!=st.end(); it++)
{
string tmp=*it;
mp[tmp]=++i;
}
for(i=1; i<=N; i++)
{
int u=fid(mp[ss[i].x]), v=fid(mp[ss[i].y]), ans=0;
if(u!=v)
{
ans=num[u]+num[v];
printf("%d\n", ans);
root[u]=v;
num[v]+=num[u];
}
else
{
ans=num[u];
printf("%d\n", ans);
}
}
}
}
return 0;
}