4.10 每日一题题解

加边的无向图

涉及知识点:

  • 并查集/dfs

solution:

  • \(题意可以理解为有多少个联通分量\)
  • \(最简单的就是并查集\)
  • \(求出来所有点可以形成多少不相交的集合,答案就是集合的个数减1\)
  • \(dfs的做法就是for循环遍历[1,n],记录遍历过的点,答案也是需要dfs的点的个数减1\)

std:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>

using namespace std;

const int N = 1000100;

int f[N];

int Find(int x){
    return f[x] == x ? x : f[x] = Find(f[x]);
}
int main(){
    int n, m;
    scanf("%d%d",&n,&m);
    for (int i = 1; i <= n; i ++) f[i] = i;
    for (int i = 0; i < m ;i ++){
        int x, y;
        scanf("%d%d",&x,&y);
        int a = Find(x);
        int b = Find(y);
        if (a != b){
            f[a] = b;
        }
    }
    int res = 0;
    set<int> s;
    for (int i = 1; i <= n; i++){
        s.insert(Find(i));
    }
    printf("%d\n",s.size() - 1);
    return 0;
}
posted @ 2020-04-10 09:51  QFNU-ACM  阅读(87)  评论(0编辑  收藏  举报