hdu 3172 Virtual Friends(并查集,字典树)
2013-10-24 13:39
417 查看
题意:人与人交友构成关系网,两个人交友,相当于两个朋友圈的合并,问每个出两人,他们目前所在的关系网中的人数。
分析:用并查集,其实就是求每个集合当前的人数。对于人名的处理用到了字典树。
注意:1、题目给出的n是指n对关系,上限有2*n个人。
2、题目很没有意思的既说了有多组数据,又要求输入组数。实际上还是多组数据。
View Code
分析:用并查集,其实就是求每个集合当前的人数。对于人名的处理用到了字典树。
注意:1、题目给出的n是指n对关系,上限有2*n个人。
2、题目很没有意思的既说了有多组数据,又要求输入组数。实际上还是多组数据。
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int MAXN=200002; struct Node{ int c; Node *child[52]; Node(){ c=0; for(int i=0;i<52;i++) child[i]=NULL; } }*root; int cnt; int p[MAXN],num[MAXN]; char str1[22],str2[22]; void init(int n) { root=new Node();// cnt=0; for(int i=0;i<n;i++) { p[i]=i; num[i]=1; } } int ID(char str[]) { Node *p=root; int len=strlen(str); for(int i=0,k;i<len;i++,p=p->child[k]) { if(str[i]>='a'&&str[i]<='z') k=str[i]-'a'; else k=str[i]-'A'+26; if(p->child[k]==NULL) p->child[k]=new Node(); } if(p->c) return p->c; return p->c=++cnt;// } int find(int x) { return p[x]==x?x:p[x]=find(p[x]); } int main() { int T,n; while(~scanf("%d",&T)) { while(T--) { scanf("%d",&n); init(n*2);// for(int i=0;i<n;i++) { scanf("%s%s",str1,str2); int u=ID(str1); int v=ID(str2); int fu=find(u); int fv=find(v); if(fu==fv) printf("%d\n",num[fu]); else { p[fv]=fu; num[fu]+=num[fv]; printf("%d\n",num[fu]); } } } } return 0; }
View Code
相关文章推荐
- hdu 3172 Virtual Friends (并查集 + 字典树)
- hdu 3172 Virtual Friends(加权并查集)
- HDU 3172 Virtual Friends(带权并查集)
- 并查集 HDU 3172 Virtual Friends
- HDU 3172 Virtual Friends 带权并查集 -秩
- HDU 3172 Virtual Friends(并查集)
- HDU 3172 Virtual Friends (并查集与map的运用,同HDU1829)
- HDU 3172 Virtual Friends(带权并查集,map)
- hdu 3172 Virtual Friends(并查集)
- hdu 3172 virtual friends 并查集
- HDU 3172 Virtual Friends (并查集节点统计)
- hdu 3172 Virtual Friends (并查集)
- HDU 3172 Virtual Friends (并查集)
- hdu 3172 Virtual Friends(并查集)University of Waterloo Local Contest 2008.09
- HDU - 3172 Virtual Friends(并查集)
- HDU 并查集 - 3172 Virtual Friends
- HDU 3172 并查集-Virtual Friends
- HDU 3172 Virtual Friends // 并查集,字典树
- hdu 3172 Virtual Friends(简单并查集)
- HDU 3172 Virtual Friends (并查集)