标签:stream amp 信息 集合 class lines tchar orm int
Input
Output
Sample Input
1 5 5 A 1 2 D 1 2 A 1 2 D 2 4 A 1 4
Sample Output
Not sure yet. In different gangs. In the same gang.
1 /* 2 Name: Find them, Catch them 3 Copyright: 4 Author: 5 Date: 09/08/17 09:27 6 Description: 给定两个集合,通过已给信息,判断两个元素是否同一集合。 7 如果是,则输出 "In the same gang." 8 如果不是,则输出"In different gangs." 9 如果不能从已给信息判断,则输出 "Not sure yet." 10 */ 11 #include<iostream> 12 #include<algorithm> 13 #include<stdio.h> 14 using namespace std; 15 const int N = 500005; 16 int parent[N],rank[N]; 17 18 void init() /*初始化*/ 19 { 20 for(int i = 0; i < N; i++) 21 { 22 parent[i] = i; 23 rank[i] = -1; 24 } 25 26 } 27 int find(int n) 28 { 29 if(n !=parent[n]) 30 parent[n] = find(parent[n]); 31 return parent[n]; 32 } 33 /* 34 使用这个函数竟然给我TLE = =、 35 int find(int n) 36 { 37 if(n == parent[n]) 38 return n; 39 else 40 return find(parent[n]); 41 } 42 */ 43 void merge(int a,int b) 44 { 45 a = find(a); 46 b = find(b); 47 if(a != b) 48 parent[a] = b; 49 } 50 int main() 51 { 52 int t,m,n,a,b; 53 char ch; 54 while(cin>>t) 55 { 56 while(t--) 57 { 58 int temp = 0; 59 init(); 60 scanf("%d %d",&n,&m); 61 for(int i = 0; i < m; i++) 62 { 63 getchar(); 64 scanf("%c %d %d",&ch,&a,&b); 65 //cin>>Node[i].ch>>Node[i].a>>Node[i].b; 在循环次数较多情况下使用scanf 使用cin容易TLE! 66 if(ch == ‘D‘) 67 { 68 if(rank[a] != -1) merge(rank[a],b); 69 if(rank[b] != -1) merge(rank[b],a); 70 rank[a] = b; 71 rank[b] = a; 72 73 }else{ 74 if( find(a) == find(b)) 75 printf("In the same gang.\n"); 76 else if(find(rank[a]) == find(b)) 77 printf("In different gangs.\n"); 78 else 79 printf("Not sure yet.\n"); 80 } 81 } 82 } 83 } 84 return 0; 85 }
标签:stream amp 信息 集合 class lines tchar orm int
原文地址:http://www.cnblogs.com/jj81/p/7325115.html