hdu5883 The Best Path

題面在這裏

題意:

問一個無向圖是否有歐拉路徑,並且有的話使得經過的點的權值異或和最大,輸出這個異或值。

做法:

首先判圖是否連通。
然後度爲奇數的點只能有0個或2個。
發現一個性質:(度+1)/2是奇數的點都是在路徑上的。
如果度爲奇數的點有2個就一個是起點一個是終點,如果0個說明有歐拉回路,則所有點都可以取爲起點,枚舉一遍選最大值即可。

代碼:

/*************************************************************
    Problem: hdu 5883 The Best Path
    User: fengyuan07
    Language: C++
    Result: Accepted
    Time: 1450MS
    Memory: 4720K
    Submit_Time: 2018-01-24 10:53:59
*************************************************************/

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cctype>
#include<cstdlib>
#include<cmath>
using namespace std;
typedef long long ll;

inline ll read() {
    char ch = getchar(); ll x = 0; int op = 1;
    for(; !isdigit(ch); ch = getchar()) if(ch == '-') op = -1;
    for(; isdigit(ch); ch = getchar()) x = x*10+ch-'0';
    return x*op;
}
inline void write(ll a) {
    if(a < 0) putchar('-'), a = -a;
    if(a >= 10) write(a/10); putchar('0'+a%10);
}

const int N = 100010, M = 500010;
int n, m;
int a[N], d[N], fa[N];

inline int getfa(int x) { return fa[x] == x ? x : fa[x] = getfa(fa[x]); }
int main() {
    int test; test = read();
    while(test --) {
        n = read(), m = read();
        for(int i = 1; i <= n; i ++) a[i] = read(), fa[i] = i;
        memset(d, 0, sizeof d);
        for(int i = 1; i <= m; i ++) {
            int x = read(), y = read(), fx, fy;
            d[x] ++, d[y] ++;
            fx = getfa(x); fy = getfa(y);
            if(fx != fy) fa[fx] = fy;
        } bool flag = 1; int st = 0;
        for(int i = 1; i <= n; i ++)
            if(d[i]) { st = i; break; }
        for(int i = 1; i <= n; i ++) {
            if(!d[i]) continue;
            if(getfa(i) != getfa(st)) { flag = 0; break; }
        }
        if(!flag) { puts("Impossible"); continue; } int odd_tot = 0;
        for(int i = 1; i <= n; i ++)
            if(d[i]&1) odd_tot ++;
        if(odd_tot != 0 && odd_tot != 2) { puts("Impossible"); continue; }
        int tmp = 0, ans = 0;
        for(int i = 1; i <= n; i ++)
            if((d[i]+1)/2%2) tmp ^= a[i];
        if(odd_tot == 0) for(int i = 1; i <= n; i ++) ans = max(ans, tmp^a[i]);
        else ans = tmp;
        printf("%d\n", ans);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章