CF1594D. The Number of Imposters 1700 ——种类并查集*

题目链接

和POJ1417相似

题意:

思路: 

种类并查集, 具体见代码

注意判断矛盾的方法:如果两个节点的属于同一个集合 判断的是它们而不是它们的根节点(代码68行)

最后统计个数的方法需要更加熟练!

// Decline is inevitable,
// Romance will last forever.
#include <bits/stdc++.h>
using namespace std;
//#define mp make_pair
#define pii pair<int,int>
#define pb push_back
#define fi first
#define se second
#define ll long long
#define LL long long
//#define int long long
const int maxn = 3e5 + 10;
const int maxm = 1e3 + 10;
const int INF = 0x3f3f3f3f;
const int dx[] = {0, 0, -1, 1}; //{0, 0, 1, 1, 1,-1,-1,-1}
const int dy[] = {1, -1, 0, 0}; //{1,-1, 1, 0,-1, 1, 0,-1}
const int P = 1e9 + 7;
int n, m;
int fa[maxn];
int vis[maxn];
int cnt[maxn];
int cnt2[maxn];
map<int, int> mp;
struct node {
    int fa;
    int re; //0表示和根节点同类 1表示反类
}a[maxn];
int ans;
int find(int x){             //查找x的祖先
    if(x == a[x].fa) return x;
    int tmp = a[x].fa;
    a[x].fa = find(a[x].fa);
    a[x].re = (a[x].re + a[tmp].re) % 2;
    return a[x].fa;
}
void merge(int x, int y){       //把y合并到x家族
    int fx = find(x);
    int fy = find(y);
    if(fx != fy) {
        fa[fx] = fy;
        
    }
}
void init() {
    for(int i=1; i <= n; i++) {
        a[i].fa = i;
        a[i].re = 0;
        vis[i] = cnt[i] = cnt2[i] = 0;
    }
    ans = 0;
}
void solve() {
    mp.clear();
    cin >> n >> m;
    init();
    bool ok = true;
    while(m--) {
        int u, v;
        string s;
        cin >> u >> v >> s;
        int d = 1;
        if(u == v) continue;
        if(s[0] == 'c') d = 0;
        int fx = find(u);
        int fy = find(v);
        if(fx == fy) {
            if((a[u].re + a[v].re) % 2 != d)
            ok = false;
        }
        else if(fx != fy) {
            a[fy].fa = fx;
            a[fy].re = (a[u].re + a[v].re + d) % 2;
            
        }
    }
    if(!ok) {
        cout << -1 << '\n';
        return;
    }
    int p = 0;
    for(int i = 1; i <= n; i++) {
        int fx = find(i);
        if(!vis[fx]) {
            mp[fx] = ++p;
            vis[fx] = 1;
        }
    }
    for(int i = 1; i <= n; i++) {
        int fx = find(i);
        cnt[mp[fx]]++;
        if(a[i].re == 1) cnt2[mp[fx]]++;
    }
    ans = 0;
    for(int i = 1; i <= p; i++) {
        ans = ans + max(cnt2[i], cnt[i] - cnt2[i]);
    }
    cout << ans << '\n';
}
int main() {
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//    int T; scanf("%d", &T); while(T--)
//    freopen("1.txt","r",stdin);
//    freopen("2.txt","w",stdout);
    int T; cin >> T;while(T--)
    solve();
    return 0;
}
/*
 
 
 
 */

猜你喜欢

转载自blog.csdn.net/m0_59273843/article/details/120982317