zoj-1097-code the tree

参考题解: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值