L3-003 并查集

之前一直部分正确,后来在输入N后面加了一个getchar()后就通过了。


上代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<set>
#include<algorithm>
using namespace std;
int father[1004];
int father_x[1004];
struct DD
{
  int num;
  int people;
};
DD fans[1004];
void init()
{
  for(int i=0;i<=1002;i++) {
    father[i]=i;
    father_x[i]=0;
  }
}
int getfather(int x)
{
  if(father[x]!=x) father[x]=getfather(father[x]);
  return father[x];
  
}
void un(int a,int b)
{
  a=getfather(a);
  b=getfather(b);
  if(a!=b){
    father[b]=a;
  }
}
int N;
int t1,t2;
bool com(DD x,DD y)
{
  if(x.people>y.people){
    return true;
  }
  if(x.people<y.people) return false;
  return true;
}
int main()
{
  scanf("%d",&N);
  init();
  getchar();
  for(int i=1;i<=N;i++)
  {
    scanf("%d",&t1);
    getchar();
    for(int j=1;j<=t1;j++)
    {
    scanf("%d",&t2);
    if(father_x[t2]<0) un(i,-father_x[t2]);
    else father_x[t2]=-i;
    }
    
  }
  for(int i=0;i<=N;i++) {
    fans[i].num=i;
    fans[i].people=0;
  }
  int te;
  for(int i=1;i<=N;i++)
  {
    te=getfather(i);
    fans[te].people++;
    //cout<<te<<endl;
  }
  sort(fans+1,fans+N+1,com);
  int ans=0;
  for(int i=1;i<=N;i++)
  {
    if(fans[i].people>0) ans++;
  }
  printf("%d\n",ans);
  for(int i=1;i<=ans;i++)
  {
    printf("%d",fans[i].people);
    if(i<ans) printf(" ");
  }
}