哥尼斯堡的“七桥问题”(25 分)
1 /* 2 5-32 哥尼斯堡的“七桥问题” (25分) 3 http://pta.patest.cn/pta/test/15/exam/4/question/859 4 并查集(用来判断是否连通) 和 一笔画(每个节点的度必须为偶数) 5 */ 6 #include <cstdio> 7 #include <cstdlib> 8 #include <iostream> 9 #include <vector> 10 #include <queue> 11 #include <map> 12 #include <algorithm> 13 #include <set> 14 #include <string> 15 16 using namespace std; 17 18 #define N 1005 19 20 int n , m ; 21 22 int degree[N] ; 23 int fa[N] ; 24 25 int find(int x) 26 { 27 if(x == fa[x]) 28 return x ; 29 return fa[x] = find(fa[x]); 30 } 31 32 void merg(int x, int y) 33 { 34 fa[find(y)] = find(x) ; 35 } 36 37 int main() 38 { 39 //freopen("in.txt","r",stdin); 40 //freopen("out.txt","w",stdout); 41 int i , u , v; 42 while( scanf("%d%d",&n,&m) != EOF) 43 { 44 for(i = 1 ; i<= n ; i++) 45 { 46 fa[i] = i ; 47 degree[i] = 0 ; 48 } 49 for(i = 0 ; i< m ; i++) 50 { 51 scanf("%d%d",&u,&v); 52 degree[u] ++; 53 degree[v] ++; 54 if(find(u) != find(v)) 55 merg(u ,v); 56 } 57 58 bool flag1 = true; 59 for(i = 1 ;i <= n ; i++) 60 { 61 if(degree[i] % 2 != 0) 62 { 63 flag1 = false ; 64 break; 65 } 66 } 67 if(flag1) 68 { 69 set<int> faset ; 70 for(i = 1 ;i <= n ; i++) 71 { 72 faset.insert(find(i)); 73 } 74 if((int)faset.size() == 1) 75 { 76 printf("1\n"); 77 }else{ 78 printf("0\n"); 79 } 80 }else{ 81 printf("0\n"); 82 } 83 } 84 return 0 ; 85 }
- /*
- 5-32 哥尼斯堡的“七桥问题” (25分)
- http://pta.patest.cn/pta/test/15/exam/4/question/859
- 并查集(用来判断是否连通) 和 一笔画(每个节点的度必须为偶数)
- */
- #include <cstdio>
- #include <cstdlib>
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <map>
- #include <algorithm>
- #include <set>
- #include <string>
- using namespace std;
- #define N 1005
- int n , m ;
- int degree[N] ;
- int fa[N] ;
- int find(int x)
- {
- if(x == fa[x])
- return x ;
- return fa[x] = find(fa[x]);
- }
- void merg(int x, int y)
- {
- fa[find(y)] = find(x) ;
- }
- int main()
- {
- //freopen("in.txt","r",stdin);
- //freopen("out.txt","w",stdout);
- int i , u , v;
- while( scanf("%d%d",&n,&m) != EOF)
- {
- for(i = 1 ; i<= n ; i++)
- {
- fa[i] = i ;
- degree[i] = 0 ;
- }
- for(i = 0 ; i< m ; i++)
- {
- scanf("%d%d",&u,&v);
- degree[u] ++;
- degree[v] ++;
- if(find(u) != find(v))
- merg(u ,v);
- }
- bool flag1 = true;
- for(i = 1 ;i <= n ; i++)
- {
- if(degree[i] % 2 != 0)
- {
- flag1 = false ;
- break;
- }
- }
- if(flag1)
- {
- set<int> faset ;
- for(i = 1 ;i <= n ; i++)
- {
- faset.insert(find(i));
- }
- if((int)faset.size() == 1)
- {
- printf("1\n");
- }else{
- printf("0\n");
- }
- }else{
- printf("0\n");
- }
- }
- return 0 ;
- }
来源:https://www.cnblogs.com/caiyishuai/p/8536177.html