1 solutions

  • 0
    @ 2022-4-6 22:28:54

    1、如果读入是敌人,就记录下来

    2、如果读入是队友,直接合并

    3、读入数据完成后,将敌人的敌人合并为一个集合

    4、最后循环判断集合数即可

    #include <stdio.h>
    #include <math.h>
    #include <algorithm>
    #include <iostream>
    #include <string.h>
    #include <queue>
    #include <stack>
    #include <map>
    #include <set>
    #include <vector>
    using namespace std;
    #define ll long long
    int n,m;
    char t;
    int fa[5007];
    vector<int> b[5007];
    int vis[5007];
    void init() {
        for(int i=1; i<=n; i++) {
            fa[i]=i;
        }
    }
    int find(int x) {
        int temp=x;
        while(fa[temp]!=temp) {
            temp=fa[temp];
        }
        while(x!=fa[x]) {
            int re=fa[x];
            fa[x]=temp;
            x=re;
        }
        return x;
    }
    void merge(int x,int y) {
        int u=find(x);
        int v=find(y);
        if(u!=v) {
            fa[u]=v;
        }
    }
    int main() {
        cin>>n>>m;
        init();
        for(int i=0; i<m; i++) {
            cin>>t;
            if(t=='E') {
                int temp=0;
                cin>>temp;
                int xx;
                cin>>xx;
                b[temp].push_back(xx);
            } else {
                int temp=0,xx=0;
                cin>>temp>>xx;
                merge(temp,xx);
            }
        }
        for(int i=1; i<=n; i++) {
            for(int j=0; j+1<b[i].size(); j++) {//防止越界的方法就是 j+1<b[i].size()
                if(b[i][j]!=0&&b[i][j+1]!=0) {//越界的数值不是0,而是随机的数值
                    merge(b[i][j],b[i][j+1]);
                } else
                    break;
            }
        }
        int ans=0;
        for(int i=1; i<=n; i++) {
            int temp=find(i);
            if(!vis[temp]) {
                vis[temp]=1;
                ans++;
            }
        }
        cout<<ans<<endl;
        return 0;
    }
    

    Information

    ID
    1261
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    6
    Tags
    # Submissions
    60
    Accepted
    19
    Uploaded By