团伙 封锁阳光大学

团伙

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 2e5+7;
int fa[maxn],en[maxn],size[maxn];
int n,m;
int find(int x)  
{  
    if (fa[x] == x) return x;
    return fa[x] = find(fa[x]); 
}

void merge(int x, int y)
{
    int fx = find(x);
    int fy = find(y);
    if (fx == fy) return;
    if (size[fx]<size[fy]) swap(fx, fy);  
    size[fx]+=size[fy];
    fa[fy] = fx;
    return;
}

int main(){
    cin>>n>>m;
    for(int i = 1;i <= n;i ++){
        fa[i] = i;
        size[i]=1;
    }
    for(int i = 1;i <= m;i ++){
        char a;int b,c;
        cin>>a>>b>>c;
        if(a == 'F'){
            merge(b,c);
            if(!en[b]&&!en[c]) merge(en[b],en[c]);
        }
        if(a == 'E'){
            if(en[c]!=0) merge(b,en[c]); 
            if(en[b]!=0) merge(c,en[b]);
            en[b]=c;en[c]=b;
        }
    }
    int ans = 0;
    for(int i = 1;i <= n;i ++){
        if(fa[i] == i) ans++;        
    }
    cout<<ans<<endl;
    return 0;
}

封锁阳光大学

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=100007;
int enm[maxn],fa[maxn],ff,ans,sz[maxn];
bool vis[maxn];
int find(int a){
    if(fa[a]==a) return fa[a];
    return fa[a]=find(fa[a]);
}
void merge(int a,int b){
    int aa=find(a);
    if(aa!=b){
        fa[b]=aa;
        sz[aa]+=sz[b];
    }
}
int main(){
    int n,m;cin>>n>>m;
    for(int i=1;i<=n;i++) {sz[i]=1;fa[i]=i;}
    for(int i=1;i<=m;i++){
        int u,v;cin>>u>>v;
        int uu=find(u),vv=find(v);
        if(uu!=vv){
            if(enm[u]) merge(enm[u],vv);
            if(enm[v]) merge(enm[v],uu);
            enm[u]=vv;enm[v]=uu;
        }
        if(uu==vv){
            cout<<"Impossible"<<endl;
            return 0;
        }
    }
    for(int i=1;i<=n;i++){
        int ff=find(i);
        if(!vis[ff]){
            int pp=find(enm[i]);
            vis[ff]=true;vis[pp]=true;
            ans+=min(sz[ff],sz[pp]);
        }
    }
    cout<<ans<<endl;
    return 0;
    
}

 

posted @ 2018-08-10 13:20  lcan  阅读(137)  评论(0编辑  收藏  举报