码迷,mamicode.com
首页 > 其他好文 > 详细

HDU5883 The Best Path(欧拉回路 | 通路下求XOR的最大值)

时间:2016-10-05 21:47:35      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5883

思路:

  先判断原图是否是欧拉回路或者欧拉通路.是的话如果一个点的度数除以2是奇数则可以产生一个XOR贡献值.之后如果是欧拉通路, 则答案是固定的,起点和终点需要多产生一次贡献值. 如果是欧拉回路, 则需要枚举起点.

代码:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cstring>
 5 #include <cmath>
 6 
 7 using namespace std;
 8 typedef long long LL;
 9 const int MAXN = 100000;
10 const int MAXE = 500000;
11 int a[MAXN + 3], deg[MAXN + 3], pre[MAXN + 3], t, n, m;
14 
15 int Find(int x) { return x == pre[x] ? x : pre[x] = Find(pre[x]); }
16 
17 void mix(int  x, int y) {
18     int fx = Find(x), fy = Find(y);
19     if(fx != fy) pre[fx] = fy;
20 }
21 
22 int isEulr(int n) {
23     int cnt1 = 0, cnt2 = 0;
24     for(int i = 1; i <= n; i++) {
25         if(deg[i] & 1) cnt1++;
26         if(pre[i] == i) cnt2++;
27     }
28     if( (cnt1 == 2 || cnt1 == 0) && cnt2 == 1) return cnt1; //cnt1 为 0 代表欧拉回路, 为 2 代表欧拉通路
29     return -1;
30 }
31 
32 int main(){34     scanf("%d", &t);
35     while(t--) {
36         memset(a, 0, sizeof(a));
37         memset(deg, 0, sizeof(deg));39         scanf("%d%d", &n, &m);
40         for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
41         for(int i = 0; i <= n; i++) pre[i] = i;
42         int u, v, k;
43         for(int i = 0; i < m; i++) {
44             scanf("%d%d", &u, &v);
45             deg[u]++, deg[v]++;
46             mix(u, v);
47         }
48         if( (k = isEulr(n) ) >= 0) {
49             int ans = 0;
50             for(int i = 1; i <= n; i++) ans ^= ( (deg[i] / 2) & 1 ? a[i] : 0 ) ;
51             if(k == 2)for(int i = 1; i <= n; i++)  { if(deg[i] & 1) ans ^= a[i]; }//欧拉通路,起点和终点需要多XOR一次
52             else  for(int i = 1; i <= n; i++)  ans = max(ans, ans ^ a[i]); //欧拉回路, 枚举下起点    
53             printf("%d\n", ans);
54         }
55         else printf("Impossible\n");
56     }
57     return 0;
58 }

 

HDU5883 The Best Path(欧拉回路 | 通路下求XOR的最大值)

标签:

原文地址:http://www.cnblogs.com/Ash-ly/p/5932748.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!