bzoj2115: [Wc2011] Xor

题目链接

bzoj2115: [Wc2011] Xor

题解

问题有环,首先我们不考虑率环,得到一条最优路径
那么,我们只需要要把在线性基上贪心的取环的贡献就好了,显然,我们沿着路径来回得到环的异或价值
我们可以任意的取一个到n的路径然后对于所有环构成的线性基贪心
这为什么是对的呢,任意取得如果不优呢
如果不优的话,选取的这台路径与最优路径是构成环的,那么异或之后首先搜出的路径价值就没了

代码

#include<cstdio> 
#include<algorithm> 
#define LL long long 
inline LL read() { 
	LL x = 0;//,f = 1; 
	char c = getchar(); 
	while(c < '0' || c > '9') c = getchar(); 
	while(c <= '9' && c >= '0') x = x * 10 + c - '0',c = getchar(); 
	return x ;//* f; 	
} 
#define int long long 
const int maxn = 1000007; 
int n,m; 
int head[maxn],num = 0; 
struct Edge { 
	int v,next;LL w;  
} edge[maxn << 1]; 
inline void add_edge(int u,int v,LL w) { 
	edge[++ num].v = v;edge[num].w = w;edge[num].next = head[u];head[u] = num; 
} 
LL dis[maxn]; LL b[90]; 
void insert(LL x) {
	for(LL i = 62;i >= 0;-- i) 
		if((x >> i) & 1) { 
			if(!b[i]) {b[i] = x;return;} 
			x = x ^ b[i]; 
		} 
} 
bool vis[maxn]; 
void dfs(int x,int fa) { 
	vis[x] = true; 
	for(int i = head[x];i;i = edge[i].next) {  
		int v = edge[i].v; 
		if(v == fa)continue; 
		if(vis[v]) {insert(dis[x] ^ dis[v] ^ edge[i].w);continue;} 
		dis[v] = dis[x] ^ edge[i].w; 
		dfs(v,x); 	
	}  
} 

main() { 
	n = read(),m = read(); 
	for(int u,v,i = 1;i <= m;++ i) { 
		u = read() ,v = read();LL w = read(); 
		add_edge(u,v,w);add_edge(v,u,w); 
	} 
	dfs(1,0); 	
	LL ans = dis[n]; 
	for(int i = 62;i >= 0;i --) 
		if((ans ^ b[i]) > ans) ans ^= b[i]; 
	printf("%lld\n",ans); 
	return 0; 
} 
 

posted @ 2018-06-24 22:15  zzzzx  阅读(113)  评论(0编辑  收藏  举报