Codeforces Round #726 (Div. 2) F. Figure Fixing 二分图性质

原题链接:https://codeforces.ml/contest/1537/problem/F

题意

有一个n个节点m条边的图,每个点上都有权值ai,现在你可以对相邻点对同时加上或减去一个数,问是否能将所有ai变成理想的bi。

分析

我们先把改变值累加 s u m = ∑ ∣ b i − c i ∣ sum=\sum |bi-ci| sum=bici,因为我们是对两个数同时操作的,因此sum只能同时加或减某个偶数。然后我们发现另一个关键性质,就是我们可以对奇数距离的点进行同加操作,对偶数距离的点进行一加一减操作,转化一下就是在二分图中,对同一个集合内的点进行一增一减,对不同集合的数同加,那么如果两个集合的sum之和不相等就永远无法达到目的。当然,如果不是二分图,那么在满足第一个条件之后肯定符合要求。

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const ll INF = 1e18;
const int N = 4e5 + 10;
const int M = 1000010;
const int MOD = 1e9 + 7;
int fa[N];
int a[N], b[N];
int find(int x) {return x == fa[x] ? x : fa[x] = find(fa[x]);}
void solve () {
    int T; cin >> T; while (T--) {
        int n, m; cin >> n >> m;
        for (int i = 1; i <= n; i++) cin >> a[i];
        for (int i = 1; i <= n; i++) cin >> b[i];
        ll sum = 0;
        for (int i = 1; i <= n; i++) sum += b[i] - a[i];
        for (int i = 1; i <= 2*n; i++) fa[i] = i;
        for (int i = 1; i <= m; i++) {
            int u, v; cin >> u >> v;
            fa[find(u)] = find(v+n);
            fa[find(v)] = find(u+n);
        }
        sum = abs(sum);
        if (sum % 2 == 1) {
            cout << "NO" << endl;
            continue;
        }
        int flag = 0;
        for (int i = 1; i <= n; i++) if (find(i) == find(i+n)) flag = 1;
        if (flag) cout << "YES" << endl;
        else {
            ll c = 0;
            for (int i = 1; i <= n; i++) if (find(i) == find(1)) c += b[i]-a[i]; else c -= b[i] - a[i];
            if (c != 0) cout << "NO" << endl;
            else cout << "YES" << endl;
        }
    }
}
signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#ifdef ACM_LOCAL
    freopen("input", "r", stdin);
    freopen("output", "w", stdout);
    signed test_index_for_debug = 1;
    char acm_local_for_debug = 0;
    do {
        if (acm_local_for_debug == '$') exit(0);
        if (test_index_for_debug > 20)
            throw runtime_error("Check the stdin!!!");
        auto start_clock_for_debug = clock();
        solve();
        auto end_clock_for_debug = clock();
        cout << "Test " << test_index_for_debug << " successful" << endl;
        cerr << "Test " << test_index_for_debug++ << " Run Time: "
             << double(end_clock_for_debug - start_clock_for_debug) / CLOCKS_PER_SEC << "s" << endl;
        cout << "--------------------------------------------------" << endl;
    } while (cin >> acm_local_for_debug && cin.putback(acm_local_for_debug));
#else
    solve();
#endif
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值