参考题解: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 vertice
int value;
//number of characters
int chNum;
int pos = 0;
int len = strlen(str);
//father
int y;
//son
int x;
//stack
stack<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++;
}
else
pos++;
}
}
int main()
{
freopen("input.in", "r", stdin);
freopen("output.out","w", stdout);
while( gets( str ) )
{
//the number of vertices
int sum = 0;
//the father
int y;
//the son
int 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;
}