美文网首页
sicily1034 Forest

sicily1034 Forest

作者: 肥宅_Sean | 来源:发表于2018-01-10 17:22 被阅读0次

模拟一个森林,找森林的宽度和深度

#include <iostream>
using namespace std;
#include <vector>
#include <cstring>

int main(){
    int n,m,a,b;
    while (cin >> n>> m && n) {
        vector<int> node[101]; // 找儿子 
        bool visited[101];     // 找爸爸 (是否有爸爸)
        memset(visited, false, sizeof(visited));
        bool twoFather = false, haveRoot = true;
        for(int i = 0; i < m; ++i) {
            cin >> a>> b;
            node[a-1].push_back(b-1); // a的儿子有b 
            if (visited[b-1]) twoFather = true;
            else visited[b-1] = true; 
        }
        vector<int> next, now;
        for (int i = 0; i < n; ++i) if (!visited[i]) now.push_back(i); 
        if (now.empty() || twoFather){
            cout << "INVALID\n"; continue;
        } 
        int depth = -1, width = 0, time = 0;
        while(!now.empty() && time <= n+1) {
            depth++;
            if (now.size() > width) width = now.size();
            for (int i = 0; i < now.size(); ++i) {
                time++;
                for (int j = 0; j < node[now[i]].size(); ++j) next.push_back(node[now[i]][j]); 
            }
            now = next;
            next.clear();
        } 
        if (time == n){
            cout << depth<< " "<< width<< endl;
        } else {
            cout << "INVALID\n";
        }
    }   
} 

相关文章

网友评论

      本文标题:sicily1034 Forest

      本文链接:https://www.haomeiwen.com/subject/qyoonxtx.html