标签:
Time Limit: 10000MS | Memory Limit: 65536K | |
Total Submissions: 30130 | Accepted: 9869 |
Description
Input
Output
Sample Input
2 3 3 1 2 2 3 1 3 4 2 1 2 3 4
Sample Output
Scenario #1: Suspicious bugs found! Scenario #2: No suspicious bugs found!
判断两只虫子是否同性。
1 #include <iostream> 2 #include <cstdio> 3 #include <string> 4 #include <queue> 5 #include <vector> 6 #include <map> 7 #include <algorithm> 8 #include <cstring> 9 #include <cctype> 10 #include <cstdlib> 11 #include <cmath> 12 #include <ctime> 13 using namespace std; 14 15 const int SIZE = 2005; 16 int FATHER[SIZE],MARK[SIZE],RANK[SIZE]; 17 18 void ini(int); 19 int get_father(int); 20 void unite(int,int); 21 bool same(int,int); 22 23 int main(void) 24 { 25 int t,n,m,x,y,count = 0; 26 bool flag; 27 28 scanf("%d",&t); 29 while(t --) 30 { 31 count ++; 32 scanf("%d%d",&n,&m); 33 ini(n); 34 flag = false; 35 while(m --) 36 { 37 scanf("%d%d",&x,&y); 38 if(flag) 39 continue; 40 if(same(x,y)) 41 flag = true; 42 if(!MARK[x] && !MARK[y]) 43 { 44 MARK[x] = y; 45 MARK[y] = x; 46 } 47 else if(!MARK[x]) 48 { 49 MARK[x] = y; 50 unite(x,MARK[y]); 51 } 52 else if(!MARK[y]) 53 { 54 MARK[y] = x; 55 unite(y,MARK[x]); 56 } 57 else 58 { 59 unite(x,MARK[y]); 60 unite(y,MARK[x]); 61 } 62 } 63 printf("Scenario #%d:\n",count); 64 if(flag) 65 puts("Suspicious bugs found!"); 66 else 67 puts("No suspicious bugs found!"); 68 puts(""); 69 } 70 71 72 return 0; 73 } 74 75 void ini(int n) 76 { 77 for(int i = 1;i <= n;i ++) 78 { 79 MARK[i] = RANK[i] = 0; 80 FATHER[i] = i; 81 } 82 } 83 84 int get_father(int n) 85 { 86 if(n == FATHER[n]) 87 return n; 88 return FATHER[n] = get_father(FATHER[n]); 89 } 90 91 void unite(int x,int y) 92 { 93 x = get_father(x); 94 y = get_father(y); 95 96 if(x == y) 97 return ; 98 if(RANK[x] < RANK[y]) 99 FATHER[x] = y; 100 else 101 { 102 FATHER[y] = x; 103 if(RANK[x] == RANK[y]) 104 RANK[x] ++; 105 } 106 } 107 108 bool same(int x,int y) 109 { 110 return get_father(x) == get_father(y); 111 }
标签:
原文地址:http://www.cnblogs.com/xz816111/p/4536825.html