zoj-1097-code the tree

来源:互联网 发布:淘宝u站推广 编辑:程序博客网 时间:2024/06/06 04:49
参考题解:http://www.cnblogs.com/pcoda/archive/2012/09/02/2667930.html

Code

这是一道解关于 无根树 的问题, 算法是将 叶节点 送入 优先队列, 然后从小到大遍历 叶节点, 可以用STL很方便地解决。

 

//program: code the tree// author: slowlight93//   date: 2013-08-08#include<cstdio>#include<iostream>#include<stack>#include<vector>#include<queue>#include<set>#include<cstring>#include<cstdlib>using namespace std;char str[300];void init( vector< set<int> > & adj ){//the value of a verticeint value;//number of charactersint chNum;int pos = 0;int len = strlen(str);//fatherint y;//sonint x;//stackstack<int> vertices;while( pos < len - 1 ){if( str[pos] == '(' ){sscanf(str + pos + 1, "%d%n", &value, &chNum);pos += chNum + 1;vertices.push(value);}else if( str[pos] == ')' ){x = vertices.top();vertices.pop();y = vertices.top();adj[x].insert(y);adj[y].insert(x);pos++;}elsepos++;}}int main(){freopen("input.in", "r", stdin);freopen("output.out","w", stdout);while( gets( str ) ){//the number of verticesint sum = 0;//the fatherint y;//the sonint x;vector < set<int> > adj (100, set<int>());priority_queue<int,vector<int>,greater<int> >leafs;init(adj);for(int i=1;adj[i].size();i++){sum++;if(adj[i].size() == 1)leafs.push(i);}for(int i=1;i<sum;i++){x = leafs.top();leafs.pop();y = *(adj[x].begin());adj[x].erase(y);adj[y].erase(x);if( adj[y].size() == 1)leafs.push(y);if( i > 1 )cout << " ";cout << y;}cout << endl;}return 0;}