zoukankan      html  css  js  c++  java
  • Hdu 4496 D-City

    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;

    代码如下

     1 #include<cstdio>
     2 #include<iostream>
     3 using namespace std;
     4 const int maxn = 100100;
     5 int n, m;
     6 int f[maxn], a[maxn], b[maxn], sum[maxn];
     7 void init(){
     8     for(int i = 0; i < n; i++)    f[i] = i;
     9 }
    10 int getf(int v){
    11     if(f[v] == v)   return v;
    12     else    return f[v] = getf(f[v]);
    13 }
    14 int main(){
    15     while(~scanf("%d %d", &n, &m)){
    16         init();
    17         for(int i = 1; i <= m; i++){
    18             scanf("%d %d", &a[i], &b[i]);
    19         }
    20         sum[m] = n;
    21         for(int i = m; i >= 1; i--){
    22             int t1 = getf(a[i]), t2 = getf(b[i]);
    23             if(t1 != t2){
    24                 f[t2] = t1;
    25                 sum[i - 1] = sum[i] - 1;
    26             }
    27             else{
    28                 sum[i - 1] = sum[i];
    29             }
    30         }
    31         for(int i = 1; i <= m; i++){
    32             printf("%d
    ", sum[i]);
    33         }
    34     }
    35     return 0;
    36 }
    D-City
  • 相关阅读:
    Monkey测试
    第八周作业-说说本周项目工作中的情况
    第七周作业-谈谈各种文档
    第六周作业-UML在详细设计阶段的使用心得&&UML建模与软件开发过程模型
    第五周作业-Markdown的使用心得
    第四周作业-Java Web学习心得
    第三周作业-谈谈对编程规范的认识
    第二周作业-软件工作量的估计
    支付宝-发展史及其优缺点
    三种软件的特点分析
  • 原文地址:https://www.cnblogs.com/zoom1109/p/11025180.html
Copyright © 2011-2022 走看看