zoukankan      html  css  js  c++  java
  • Ural_1671. Anansi's Cobweb(并查集)

      /*思路参考大牛,我脑袋被lv踢了,居然想到用数状数组写。。。
    思路:并查集,先把不许要删的边用并查集合并,然后把需要删的边逆序加入到并查集中。。。。

    My Code:
    */

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

    using namespace std;

    const int N = 100005;

    struct node {
    int s;
    int e;
    }g[N];

    int parent[N];
    int c[N];
    int ans[N];
    int Rank[N];
    bool vis[N];

    void init(int n) {
    for(int i = 1; i <= n; i++) {
    parent[i] = i;
    Rank[i] = 0;
    vis[i] = false;
    }
    }

    int find(int x) {
    int k, r, j;
    r = x; k = x;
    while(r != parent[r]) {
    r = parent[r];
    }
    while(k != r) {
    j = parent[k];
    parent[k] = r;
    k = j;
    }
    return r;
    }

    void union_set(int x, int y) {
    x = find(x);
    y = find(y);
    if(x == y) return;
    if(Rank[x] > Rank[y]) parent[y] = x;
    else {
    parent[x] = y;
    if(Rank[x] == Rank[y]) ++ Rank[y];
    }
    }

    int main() {
    //freopen("data.in", "r", stdin);

    int n, m, i, k, cnt;
    while(~scanf("%d%d", &n, &m)) {
    init(n); cnt = 0;
    for(i = 1; i <= m; i++) {
    scanf("%d%d", &g[i].s, &g[i].e);
    vis[i] = true;
    }

    scanf("%d", &k);
    for(i = 0; i < k; i++) {
    scanf("%d", &c[i]);
    vis[c[i]] = false;
    }

    for(i = 1; i <= m; i++) {
    if(!vis[i]) continue;
    if(find(g[i].s) != find(g[i].e)) {
    union_set(g[i].s, g[i].e);
    cnt++;
    }
    }

    for(i = k-1; i >= 0; i--) {
    ans[i] = n-cnt;
    if(find(g[c[i]].s) != find(g[c[i]].e)) {
    union_set(g[c[i]].s, g[c[i]].e);
    cnt++;
    }
    }

    for(i = 0; i < k; i++) {
    printf("%d", ans[i]);
    if(i == k-1) putchar('\n');
    else putchar('');
    }
    }
    return 0;
    }
  • 相关阅读:
    怎样用HTML5 Canvas制作一个简单的游戏
    js面向对象
    javascript闭包
    javascript变量的作用域
    5-22
    5-23
    14-5-21 硬代码
    14-5-19 类和对象
    array
    生成干扰线
  • 原文地址:https://www.cnblogs.com/vongang/p/2257632.html
Copyright © 2011-2022 走看看