zoukankan      html  css  js  c++  java
  • HDU4496(并查集)

    D-City

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
    Total Submission(s): 3665    Accepted Submission(s): 1306


    Problem Description

    Luxer is a really bad guy. He destroys everything he met. 
    One day Luxer went to D-city. D-city has N D-points and M D-lines. Each D-line connects exactly two D-points. Luxer will destroy all the D-lines. The mayor of D-city wants to know how many connected blocks of D-city left after Luxer destroying the first K D-lines in the input. 
    Two points are in the same connected blocks if and only if they connect to each other directly or indirectly.
     

    Input

    First line of the input contains two integers N and M. 
    Then following M lines each containing 2 space-separated integers u and v, which denotes an D-line. 
    Constraints: 
    0 < N <= 10000 
    0 < M <= 100000 
    0 <= u, v < N. 
     

    Output

    Output M lines, the ith line is the answer after deleting the first i edges in the input.
     

    Sample Input

    5 10
    0 1
    1 2
    1 3
    1 4
    0 2
    2 3
    0 4
    0 3
    3 4
    2 4
     

    Sample Output

    1
    1
    1
    2
    2
    2
    2
    3
    4
    5
     
     并查集,题目问每破坏一条边有多上连通块,可以倒推把边连起来,每次查询有多少个集合
     1 //2016.8.9
     2 #include<iostream>
     3 #include<cstdio>
     4 #include<stack>
     5 
     6 using namespace std;
     7 
     8 int fa[10005], arr[100005][2], cnt;
     9 
    10 int getf(int i)
    11 {
    12     if(fa[i]==i)return i;
    13     return fa[i] = getf(fa[i]);
    14 }
    15 
    16 int init(int n)
    17 {
    18     for(int i = 0; i < n; i++)
    19       fa[i] = i;
    20 }
    21 
    22 int Merge(int a, int b)
    23 {
    24     int af = getf(a);
    25     int bf = getf(b);
    26     if(af!=bf){
    27       fa[bf] = af;
    28       cnt--;
    29     }
    30 }
    31 
    32 int main()
    33 {
    34     int n, m, u, v;
    35     while(cin>>n>>m)
    36     {
    37         init(n);
    38         for(int i = 0; i < m; i++)
    39         {
    40             scanf("%d%d", &arr[i][0], &arr[i][1]);
    41         }
    42         stack<int> s;
    43         cnt = n;
    44         for(int i = m-1; i >= 0; i--)
    45         {
    46             s.push(cnt);
    47             Merge(arr[i][0], arr[i][1]);
    48         }
    49         while(!s.empty())
    50         {
    51             int ans = s.top();
    52             cout<<ans<<endl;
    53             s.pop();
    54         }
    55     }
    56 
    57     return 0;
    58 }
  • 相关阅读:
    hdu 2082 找单词
    hdu 2079 选课时间(题目已修改,注意读题)
    hdu 2073 无限的路
    hdu 2062 Subset sequence
    poj 2777 Count Color
    hdu 2067 小兔的棋盘
    卡特兰数
    poj3468
    hdu1394
    hdu1166(线段树之单点更新)
  • 原文地址:https://www.cnblogs.com/Penn000/p/5754788.html
Copyright © 2011-2022 走看看