Ba Gua Zhen
Time Limit: 1 Sec
Memory Limit: 256 MB
题目连接
无
Description
Fortunately, there was an old man named Chengyan Huang who was willing to help Xun Lu to hack the puzzle. Chengyan told Xun Lu that he had to choose a vertex as the start point, then walk through some of the edges and return to the start point at last. During his walk, he could go through some edges any times. Since Liang Zhuge had some mysterious magic, Xun Lu could hack the puzzle if and only if he could find such a path with the maximum XOR sum of all the edges length he has passed. If the he passed some edge multiple times, the length would also be calculated by multiple times. Now, could you tell Xun Lu which is the maximum XOR circuit path in this puzzle to help him hack the puzzle?
Input
Each test case begins with two integers N(2≤N≤5×104) and M(1≤M≤105) in one line. Then M lines follow. Each line contains three integers ui, vi and wi(1≤ui,vi≤N, 0≤wi≤260−1) to describe all the edges in the puzzle.
Output
Sample Input
2
3 3
1 2 1
1 3 2
2 3 0
6 7
1 2 1
1 3 1
2 3 1
3 4 4
4 5 2
4 6 2
5 6 2
Sample Output
Case #1: 3
Case #2: 3
HINT
A XOR takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. In this we perform the comparison of two bits, being 1 if the two bits are different, and 0 if they are the same.
题意
有一个n(<=50000)个顶点m(<=100000)条边的无向图,每条边有一个边权(0<=边权<2^60),求所有回路中边权xor和的最大值。
题解:
首先dfs,跑出所有环的xor值,比如里面有k个环
然后我们就可以转化为,给你k个数,让你选择任意多的数,使得异或值最大
这个要用高斯消元做:http://wenku.baidu.com/link?url=BFic5zoh7tkGkLTgrRta5OtFliMsghlACqlx-XyjMFPgLh14ujAo33SDtLbFhHYN6JoGt2b1d9XsxMP97Degfpb8QzUs_eZJNEwgbhPVScO
代码:
#include<iostream>
#include<math.h>
#include<vector>
#include<stdio.h>
#include<cstring>
using namespace std;
#define maxn 50005
vector<pair<int,long long> >G[maxn];
vector<long long> ans;
long long Xor[maxn];
int vis[maxn];
void dfs(int x,int pre,long long Ans)
{
if(vis[x])
{
long long p = Ans ^ Xor[x];
ans.push_back(p);
return;
}
vis[x]=;
for(int i=;i<G[x].size();i++)
{
int v = G[x][i].first;
if(pre == v)continue;
if(!vis[v])Xor[v]=Ans^G[x][i].second;
dfs(v,x,Ans ^ G[x][i].second);
}
}
int main()
{
int t;scanf("%d",&t);
for(int cas=;cas<=t;cas++)
{
ans.clear();
memset(vis,,sizeof(vis));
memset(Xor,,sizeof(Xor));
int n,m;scanf("%d%d",&n,&m);
for(int i=;i<=n;i++)
G[i].clear();
for(int i=;i<=m;i++)
{
int x,y;long long z;
scanf("%d%d%lld",&x,&y,&z);
G[x].push_back(make_pair(y,z));
G[y].push_back(make_pair(x,z));
}
dfs(,-,);
int k=;
for(int i=;i>=;i--)
{
int j;
for(j=k;j<ans.size();j++)
if((ans[j]&(1LL<<i))!=)
{
break;
}
if (j==ans.size()) continue;
if (j!=k)
swap(ans[k],ans[j]);
//cout<<d[j]<<endl;
for (j=k+;j<ans.size();j++)
if ((ans[j]&(1LL<<i))!=)
ans[j]^=ans[k];
k++;
}
long long Ans = ;
for(int i=;i<k;i++)
Ans = max(Ans,Ans ^ ans[i]);
printf("Case #%d: %lld\n",cas,Ans);
}
}