1. 程式人生 > >bzoj2115 [Wc2011] Xor——高斯消元 & 異或線性基

bzoj2115 [Wc2011] Xor——高斯消元 & 異或線性基

++ r+ n) 沒有 get TP pro bzoj ()

題目:https://www.lydsy.com/JudgeOnline/problem.php?id=2115

異或兩次同一段路徑的權值,就相當於沒有走這段路徑;

由此可以得到啟發,對於不同的走法,也許只需要找出一些東西,就可以把所有的走法用它們來異或表示出來;

再關註圖上的環路,因為從 1 到 n 的不同路徑也可以看作是經由 1 和 n 連接的環路,路徑上也可能有環路;

發現對於環路的不同走法,就是把路與環的權值異或求最優值,重疊的部分異或了兩次相當於不走;

於是問題轉化為找出圖上的所有環(可以用 dfs ),把它們的權值異或起來得到最優解;

這裏又有高斯消元求解線性基的套路,總之上就是了。

代碼如下:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
int const maxn=5e4+5,maxm=1e5+5;
int n,m,head[maxn],ct,cir;
ll ans,v[maxm<<1],dis[maxn];//maxm<<1
bool vis[maxn];
struct N{
    int to,next; ll w;
    N(int t=0,int n=0,ll w=0
):to(t),next(n),w(w) {} }edge[maxm<<1]; void add(int x,int y,ll z){edge[++ct]=N(y,head[x],z); head[x]=ct;} void dfs(int x) { vis[x]=1; for(int i=head[x],u;i;i=edge[i].next) { if(!vis[u=edge[i].to]) { dis[u]=(dis[x]^edge[i].w); dfs(u); }
else v[++cir]=(dis[u]^dis[x]^edge[i].w); } } void gauss() { int nw=0; for(int i=60;i>=0;i--) { // int j=++nw;//這樣寫會造成 nw 空加! int j=nw+1; while(j<=cir&&(v[j]&(1ll<<i))==0)j++; if(j==cir+1)continue; nw++; swap(v[nw],v[j]); for(int j=1;j<=cir;j++) if(j!=nw&&(v[j]&(1ll<<i)))v[j]^=v[nw]; } } int main() { scanf("%d%d",&n,&m); int x,y; ll z; for(int i=1;i<=m;i++) { scanf("%d%d%lld",&x,&y,&z); add(x,y,z); add(y,x,z); } dfs(1); gauss(); ans=dis[n]; for(int i=1;i<=cir;i++) ans=max(ans,ans^v[i]); printf("%lld",ans); return 0; }

bzoj2115 [Wc2011] Xor——高斯消元 & 異或線性基