您的位置:首页 > 其它

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

2016-08-20 19:51 162 查看


题目描述

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


输入

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


输出

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


示例输入

2 1
1 2
2 0



示例输出

1
2

#include <iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
struct PTNode
{
    int data;//类的标号;
    int parent;//当前元素的双亲结点序号(类的直接基类)
}p[101];
int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        int count=0;//统计有多少类没有直接基类;
        for(int i=1;i<=n;i++)
        {
            p[i].parent=0;//初始化
            p[i].data=i;
        }
        while(m--)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            p[y].parent=x;
        }
        for(int i=1;i<=n;i++)
            if(p[i].parent==0)//若父结点为空, 即为根节点
            count++;
        printf("%d\n",count);
    }
    return 0;
}
#include <bits/stdc++.h>

using namespace std;

int mp[110][110];//表示谁是谁的基类
int main()
{
    int n, m, s;
    int a, b;
    while(~scanf("%d %d", &n, &m))
    {
        if(m == 0)//没有直接基类;
            printf("%d\n",n);
        else
        {
            s=0;//记录有直接基类的类;
            memset(mp, 0, sizeof(mp));//初始化;
            while(m--)
            {
                scanf("%d %d", &a, &b);
                mp[a][b] = 1;//表示a是b的直接基类;
            }
            for(int i = 1; i <= n; i++)
            {
                for(int j = 1; j <= n; j++)
                {
                    if(i != j&&mp[j][i] == 1)
                    {
                        s++;
                        break;
                    }
                }
            }
            printf("%d\n", n-s);
        }
    }
    return 0;
}
#include <algorithm>
#include <stdio.h>
#include <string.h>//memset函数存在于此头文件中
using namespace std;
int main()
{
    bool st[500];//标记含有单继承关系的类(逻辑型)
    int n,m,a,b;
    while(~scanf("%d %d",&n,&m))
    {
        int cnt=n;
        memset(st,false,sizeof(st));//初始化;
        while(m--)
        {
            scanf("%d %d",&a,&b);
            if(!st[b])//b有直接基类;
            {
                st[b]=true;
                cnt--;
            }
        }
        printf("%d\n",cnt);
 }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: