码迷,mamicode.com
首页 > 其他好文 > 详细

Code the Tree ZOJ - 1097

时间:2017-07-04 14:53:57      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:分享   pre   传送门   src   技术分享   技术   tree   names   har   

传送门:https://vjudge.net/problem/ZOJ-1097

技术分享

技术分享

解题思路:

主要是找到每一节点的相邻节点,然后后面的用优先队列就行了。

#include <cstdio>
#include <queue>
#include <vector>
#include <set>
#include <iostream>
using namespace std;

void parse(vector<set<int> >&adj,unsigned int p=0){
    unsigned int x;
    cin>>x;
    if(p){
        adj[x].insert(p);
        adj[p].insert(x);
    }

    while(true){
        char ch;
        cin>>ch;
        if(ch==))
            break;
        parse(adj,x);
    }
    return ;
}

int main(){
    char ch;
    while(cin>>ch){
        vector<set<int> >adj(1020,set<int>());
        parse(adj);
        priority_queue<int,vector<int>,greater<int> >leafs;

        int n=0;
        for(int i=0;i<adj.size();i++){
            if(adj[i].size()!=0){
                n++;
                if(adj[i].size()==1){
                    leafs.push(i);
                }
            }
        }

        for(int k=1;k<n;k++){
            int x=leafs.top(); leafs.pop();

            if(k>1)
                cout<<" ";
            int p=*(adj[x].begin());
            cout<<p;
            adj[p].erase(x);
            if(adj[p].size()==1)
                leafs.push(p);
    }
     cout<<endl;
    }
    return 0;
}

 

Code the Tree ZOJ - 1097

标签:分享   pre   传送门   src   技术分享   技术   tree   names   har   

原文地址:http://www.cnblogs.com/IKnowYou0/p/7116159.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!