NewTrain1 T9:[WC2011]最大XOR和路径

题目分析

我们把选出的路径看做一条1到n的简单路径+一些环

简单路径可以任取一条,就算我们选出的这条不是最优解的路径,我们也可以认为,我们走这条路径到了n,又走最优解的路径回到1,然后再走这条路径到n,这样其实就是这条路径+一个环,异或一下就抵消了这条路径。

那么对于一个不直接与这条路径联通的环,我们也可以认为这个环可以异或到答案里面。因为从这条路一条分岔出去到这个环,然后再原路返回,那从这条路到环的那段分岔异或一下就抵消掉了,所以可以直接异或这个环。

那么解题思路就是,预处理出所有的环,将其加入线性基中。然后再计算出1到n的任意一条简单路径,长度记为d,我们在线性基中询问与d异或的最大值即可。

预处理环与计算简单路径可以一并在dfs中完成。

 1 #include<bits/stdc++.h>
 2 #define INTMAX 2147483647LL
 3 #define PII pair<int,int>
 4 #define MK make_pair
 5 #define re register
 6 using namespace std;
 7 typedef long long ll;
 8 const double Pi=acos(-1.0);
 9 const int Inf=0x3f3f3f3f;
10 const int MAXN=2e5+10;
11 
12 inline int read(){
13     re int x=0,f=1,ch=getchar();
14     while(!isdigit(ch))f=ch=='-'?-1:1,ch=getchar();
15     while(isdigit(ch))x=x*10+ch-48,ch=getchar();
16     return x*f;
17 }
18 inline ll readll(){
19     re ll x=0,f=1,ch=getchar();
20     while(!isdigit(ch))f=ch=='-'?-1:1,ch=getchar();
21     while(isdigit(ch))x=x*10+ch-48,ch=getchar();
22     return x*f;
23 }
24 
25 struct Edge{
26     int to,nxt;
27     ll d;
28 }e[MAXN<<1];
29 int cnt,head[MAXN];
30 int n,m;
31 bool vis[MAXN];
32 ll dis[MAXN],bse[70]; 
33 inline void add_edge(int u,int v,ll d){
34     e[++cnt].to=v;e[cnt].d=d;e[cnt].nxt=head[u];head[u]=cnt;
35 }
36 
37 inline void Insert(ll x){
38     for(int i=60;i>=0;--i){
39         if(x&(1ll<<i)){
40             if(bse[i]) x^=bse[i];
41             else{
42                 bse[i]=x;
43                 break;
44             }
45         }
46     }
47 }
48 inline ll Query(ll x){
49     for(int i=60;i>=0;--i){
50         if((x^bse[i])>x) x^=bse[i];
51     }
52     return x;
53 }
54 inline void dfs(int x){
55     vis[x]=true;
56     for(int i=head[x],y;i;i=e[i].nxt){
57         y=e[i].to;
58         if(vis[y]) Insert(dis[x]^dis[y]^e[i].d);
59         else{
60             dis[y]=dis[x]^e[i].d;
61             dfs(y);
62         }
63     }
64 }
65 int main(){
66     n=read();m=read();
67     for(int i=1;i<=m;++i){
68         int u=read(),v=read();
69         ll d=readll();
70         add_edge(u,v,d);
71         add_edge(v,u,d);
72     }
73     dfs(1);
74     printf("%lld\n",Query(dis[n]));
75     return 0;
76 }

猜你喜欢

转载自www.cnblogs.com/LI-dox/p/11267300.html