*浙大PAT甲级 1107 并查集
2016-09-08 14:11
330 查看
这个题目求有共同爱好的人的集体数,以及从大到小输出各个集体的人数。
并查集的思想。我的思路是:用num[i]数组表示根为爱好i的人数个数。最后排序统计不等于的num[i]有多少个,然后排序,后序输出。
AC代码:
并查集的思想。我的思路是:用num[i]数组表示根为爱好i的人数个数。最后排序统计不等于的num[i]有多少个,然后排序,后序输出。
AC代码:
#include<iostream> #include<map> #include<cstdio> #include<algorithm> #include<queue> #include<cstring> #include<set> #include<stack> #include<cmath> #include<vector> #include<hash_map> #define ll long long #define inf 24*60*60 using namespace std; int num[1005]; int father[1005]; int findroot(int x) { if(father[x]==-1) return x; else { int tmp=findroot(father[x]); father[x]=tmp; return tmp; } } int main() { int n; scanf("%d",&n); memset(num,0,sizeof(num)); memset(father,-1,sizeof(father)); for(int i=0;i<n;i++) { int d; scanf("%d:",&d); vector<int> v; for(int j=0;j<d;j++) { int c; scanf("%d",&c); v.push_back(c); } int root1=findroot(v[0]); num[root1]++; for(int i=1;i<v.size();i++) { int root2=findroot(v[i]); if(root1!=root2) { father[root2]=root1; num[root1]+=num[root2]; num[root2]=0; } } } int ans=0; for(int i=1;i<=1000;i++) { if(num[i]>0) { ans++; } } printf("%d\n",ans); sort(num,num+1001); printf("%d",num[1000]); for(int i=999;i>=1;i--) { if(num[i]>0) { printf(" %d",num[i]); } else { break; } } }
相关文章推荐
- PAT甲题题解-1107. Social Clusters (30)-PAT甲级真题(并查集)
- *浙大PAT甲级 1114 并查集
- PAT - 甲级 - 1107. Social Clusters (30) (并查集)
- PAT 甲级 1107. Social Clusters (30)
- 浙大pat | 浙大pat 牛客网甲级 1010 Build A Binary Search Tree (30) 二叉搜索树
- 浙大PAT甲级-1031
- 浙大PAT甲级 1031
- *浙大PAT甲级 1044
- *浙大PAT甲级 1065
- *浙大PAT甲级 1072 最短路径dij
- 浙大PAT甲级 1100
- 浙大PAT甲级 1102
- 浙大PAT甲级 1112
- PAT 1107. Social Clusters (30) 特殊问题+并查集+数量信息并查集
- 浙大PAT甲级-1003
- 浙大pat | 浙大pat 牛客网甲级1061 Insert or Merge (25)判断是插入排序还是归并排序
- 浙大PAT甲级-1011
- 浙大pat | 牛客网甲级 1025 Sort with Swap(0) (25)排序
- 浙大pat甲级 1023
- 浙大PAT甲级 1032