D. 0-1 MST

题意:给定一张完全图,即每个点都跟另一个点相连,然后有n个点,编号为1到n,然后有m条边的权值为1,其它边全为0,求最小生成树。

分析:使用最小生成树算法不行,因为时间复杂度太高了,每个点都和另一个点相连,大概有n * (n - 1) / 2条边,超时。我们可以采样另一种做法,我们将所有边权为0且相连的点看成一个联通块,每个联通块和其它联通块通过一条或多条边权为1的边相连,那么我们把这些联通块看成一个点,即缩点,那么我们就在新图上求最小生成树,那么这个最小生成树的答案就是联通块的个数-1,(树的性质:边数等于顶点数减一),可以画个图,因为每个点和其它所有点相连,有0和1的边,那么我们把所有边权为0且相连的点看成一个联通块,这个联通块通过很多1的边和其它连通块相连,我们只需要选择一条,就可以和其它连通块相连,其它权值为1的点都可以省去,那么就可以得到一个最小生成树。

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

using namespace std;
const int N = 100005;
set<int> k;
set<int> g[N];
bool st[N];

int n, m;

void dfs(int x)
{
    //标记为遍历过
    st[x] = true;
    k.erase(x);
    vector<int> q;
    //完全图,和其它点都相连,将所有边权为0且相连的点删去
    for (int i : k)
    {
        if (g[x].find(i) == g[x].end())
            q.push_back(i);
    }

    for (int i : q)
    {
        k.erase(i);
    }
    //遍历剩余的点
    for (int i : q)
    {
        dfs(i);
    }
}
int main()
{
    //n个点,m条边
    cin >> n >> m;

    int a, b;
    //边权为1的两个点相连
    while (m--)
    {
        cin >> a >> b;
        g[a].insert(b), g[b].insert(a);
    }

    //保存所有未遍历过的点
    for (int i = 1; i <= n; ++i)
        k.insert(i);

    int res = 0;
    for (int i = 1; i <= n; ++i)
    {
        if (!st[i])
        {
            ++res, dfs(i);
        }
    }

    cout << res - 1 << endl;
    return 0;
}





猜你喜欢

转载自www.cnblogs.com/pixel-Teee/p/12243834.html
MST