zoukankan      html  css  js  c++  java
  • 湖南多校对抗赛(2015.05.03)Problem B: War

    并查集。从后往前加边。

    #include<stdio.h>
    #include<string.h>
    #include<math.h>
    #include<algorithm>
    using namespace std;
    const int maxn = 1000000 + 10;
    int father[maxn], u[maxn], v[maxn], Q, q[maxn], ans[maxn], ff[maxn];
    int find(int x)
    {
        if (x != father[x]) father[x] = find(father[x]);
        return father[x];
    }
    int main()
    {
        int n, m, i;
        while (~scanf("%d%d", &n, &m))
        {
            memset(ff, 0, sizeof(ff));
            for (i = 0; i <= n; i++) father[i] = i;
            for (i = 1; i <= m; i++) scanf("%d%d", &u[i], &v[i]);
            scanf("%d", &Q);
            for (i = 1; i <= Q; i++){ scanf("%d", &q[i]); ff[q[i]] = 1; }
            int tot = n;//没有边的时候有n个集合
            for (i = 1; i <= m; i++)
            {
                if (ff[i] == 0)
                {
                    int uf, vf;
                    uf = find(u[i]);
                    vf = find(v[i]);
                    if (vf != uf)
                    {
                        father[vf] = uf;
                        tot--; //加入一条边,集合少一个
                    }
                }
            }
            ans[1] = tot;
            int j = 2;
            for (i = Q; i > 1; i--)
            {
                int uf, vf;
                uf = find(u[q[i]]);
                vf = find(v[q[i]]);
                if (vf != uf)
                {
                    father[vf] = uf;
                    tot--; //加入一条边,集合少一个
                }
                ans[j] = tot; j++;
            }
            for (i = Q; i >= 1; i--)
            {
                if (i > 1) printf("%d ", ans[i]);
                else printf("%d
    ", ans[i]);
            }
        }
        return 0;
    }
  • 相关阅读:
    反向迭代
    c++知识点
    LeetCode-Count Bits
    LeetCode-Perfect Rectangle
    LeetCode-Perfect Squares
    LeetCode-Lexicographical Numbers
    LeetCode-Find Median from Data Stream
    LeetCode-Maximal Square
    LeetCode-Number of Digit One
    LeetCode-Combination Sum IV
  • 原文地址:https://www.cnblogs.com/zufezzt/p/4474148.html
Copyright © 2011-2022 走看看