zoukankan      html  css  js  c++  java
  • 树结构练习——判断给定森林中有多少棵树

                                                                       树结构练习——判断给定森林中有多少棵树

    Time Limit: 1000MS Memory Limit: 65536KB

    Problem Description

     众人皆知,在编程领域中,C++是一门非常重要的语言,不仅仅因为其强大的功能,还因为它是很多其他面向对象语言的祖先和典范。不过这世上几乎没什么东西是完美的,C++也不例外,多继承结构在带来强大功能的同时也给软件设计和维护带来了很多困难。为此,在java语言中,只允许单继承结构,并采用接口来模拟多继承。KK最近获得了一份java编写的迷你游戏的源代码,他对这份代码非常感兴趣。这份java代码是由n个类组成的(本题不考虑接口),现在,他想要知道这份代码中有多少个类没有直接基类。n个类分别用数字1..n表示。
     

    Input

     输入数据包含多组,每组数据格式如下。
    第一行包含两个整数n,m,表示该份代码中的n个类和m个单继承关系。
    后面m行,每行两个整数a b,表示a是b的直接基类。

    Output

     对于每组输入,输出该组数据中有多少个类没有直接基类。每组输出占一行。
     

    Example Input

    2 1
    1 2
    2 0

    Example Output

    1
    2
    

    Hint

    #include <stdio.h>
    #include <string.h>
    int pre[123];
    void initial(int n)
    {
    for(int i=0;i<=n;i++)
    {
    pre[i] = i;
    }
    }


    int Find(int root)
    {
    int a = root;
    while(root!=pre[root])
    {
    root = pre[root];
    }
    while(pre[a]!=root)
    {
    int temp = pre[a];
    pre[a] = root;
    a = temp;
    }
    return root;
    }
    int Count(int n)
    {
    int count=0;
    for(int i=0;i<=n;i++)
    {
    int root = Find(i);
    if(root)
    {
    count++;
    pre[root] = 0;
    }
    }
    return count;
    }
    void Join(int a,int b)
    {
    int root_a = Find(a);
    int root_b = Find(b);
    if(root_a!=root_b)
    {
    if(root_a<root_b)
    {
    pre[root_a] = root_b;
    }
    else
    {
    pre[root_b] = root_a;
    }
    }
    }
    int main()
    {
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
    initial(n);
    while(m--)
    {
    int u,v;
    scanf("%d%d",&u,&v);
    Join(u,v);
    }
    printf("%d\n",Count(n));
    }
    return 0;
    }
  • 相关阅读:
    对数损失函数(Logarithmic Loss Function)的原理和 Python 实现
    ffmpeg 简介及使用
    数据预处理(Python scikit-learn)
    检查 NaN 数据值 (C/C++/Python 实现)
    数据正规化 (data normalization) 的原理及实现 (Python sklearn)
    matplotlib.pyplot 导引
    在 O(1) 时间删除链表结点(C 和 Python 实现)
    安装 Python IDLE (Linux)
    打印 1 到最大的 n 位数(C++ 和 Python 实现)
    七种RAID技术
  • 原文地址:https://www.cnblogs.com/CCCrunner/p/6444573.html
Copyright © 2011-2022 走看看