首页 > 代码库 > HDU5883 The Best Path(并查集+欧拉路)

HDU5883 The Best Path(并查集+欧拉路)

题意:

n个点m条边,问m条边构成的是否为欧拉路。
是的话输出路径上所有点的异或和,每个点经过几次异或几次。

思路:

先用并查集判断是否连通,然后如果是欧拉路的话有两种情况

如果奇数度节点有2个,就枚举这两个点做起点,选大的

如果都为偶数度节点,就枚举n个起点,选大的

/* ***********************************************Author        :devil************************************************ */#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <vector>#include <queue>#include <set>#include <stack>#include <map>#include <string>#include <cmath>#include <stdlib.h>#define inf 0x3f3f3f3f#define LL long long#define rep(i,a,b) for(int i=a;i<=b;i++)#define dep(i,a,b) for(int i=a;i>=b;i--)#define ou(a) printf("%d\n",a)#define pb push_back#define mkp make_pairtemplate<class T>inline void rd(T &x){char c=getchar();x=0;while(!isdigit(c))c=getchar();while(isdigit(c)){x=x*10+c-0;c=getchar();}}#define IN freopen("in.txt","r",stdin);#define OUT freopen("out.txt","w",stdout);using namespace std;const int mod=1e9+7;const int N=1e5+10;int cnt,a[N],deg[N];int pre[N];int fnd(int x){    int r=x;    while(pre[r]!=r) r=pre[r];    int i=x,j;    while(i!=r)    {         j=pre[i];         pre[i]=r;         i=j;    }    return r;}void join(int x,int y){    x=fnd(x),y=fnd(y);    if(x!=y)    {        pre[x]=y;        cnt--;    }}int main(){    int t,n,m,x,y;    rd(t);    while(t--)    {        rd(n),rd(m);        rep(i,1,n) rd(a[i]);        memset(deg,0,sizeof(deg));        cnt=n;        rep(i,1,n) pre[i]=i;        while(m--)        {            rd(x),rd(y);            join(x,y);            deg[x]++;            deg[y]++;        }        if(cnt>1)        {            printf("Impossible\n");            continue;        }        int con=0;        rep(i,1,n) if(deg[i]%2) con++;        if(con!=0&&con!=2)        {            printf("Impossible\n");            continue;        }        int ans=0;        if(con)        {            rep(i,1,n) if(((deg[i]+1)/2)&1) ans^=a[i];        }        else        {            int tmp=0;            rep(i,1,n) if((deg[i]/2)&1) tmp^=a[i];            rep(i,1,n) ans=max(ans,tmp^a[i]);        }        printf("%d\n",ans);    }    return 0;}

 

HDU5883 The Best Path(并查集+欧拉路)