Prufer Code_2018_2_21

3 篇文章 0 订阅
2 篇文章 0 订阅
A tree (i.e. a connected graph without cycles) with vertices is given ( N ≥ 2). Vertices of the tree are numbered by the integers 1,…, N. A Prufer code for the tree is built as follows: a leaf (a vertex that is incident to the only edge) with a minimal number is taken. Then this vertex and the incident edge are removed from the graph, and the number of the vertex that was adjacent to the leaf is written down. In the obtained graph once again a leaf with a minimal number is taken, removed and this procedure is repeated until the only vertex is left. It is clear that the only vertex left is the vertex with the number N. The written down set of integers ( N−1 numbers, each in a range from 1 to N) is called a Prufer code of the graph.
Your task is, given a Prufer code, to reconstruct a tree, i.e. to find out the adjacency lists for every vertex in the graph.
You may assume that 2 ≤  N ≤ 7500
Input
A set of numbers corresponding to a Prufer code of some tree. The numbers are separated with a spaces and/or line breaks.
Output
Adjacency lists for each vertex. Format: a vertex number, colon, numbers of adjacent vertices separated with a space. The vertices inside lists and lists itself should be sorted by vertex number in an ascending order (look at sample output).
Example

inputoutput
2 1 6 2 6
1: 4 6
2: 3 5 6
3: 2
4: 1
5: 2
6: 1 2

#include<iostream> 
#include<cstdio>
#include<queue>
#include<strstream>
#include<vector>
#include<string>
#include<algorithm>
#include<functional>
using namespace std;

typedef vector<int> vi;
typedef vector<vi> vvi;

void print(vvi &adj,int x,int p=0){
	printf("(%d",x) ;
	for(vi::iterator it=adj[x].begin();it!=adj[x].end();it++)
	if(*it!=p){
		putchar(' ');
		print(adj,*it,x);
	}
	putchar(')');
}

int main(){
	string line;
	while(getline(cin,line)){
		istrstream lstr(line.c_str());
		vi v;
		int x;
		while(lstr>>x)
		v.push_back(x);
		int n=v.size()+1;
		vi deg(n+1,0);
		for(int i=0;i<n-1;i++)
		deg[v[i]]++;
		priority_queue<int,vi,greater<int> >leafs;
		for(int i=1;i<=n;i++)
		if(deg[i]==0)leafs.push(i);
		vvi adj(n+1,vi());
		for(int i=0;i<n-1;i++){
			x=leafs.top();
			leafs.pop();
			adj[x].push_back(v[i]);
			adj[v[i]].push_back(x);
			if(--deg[v[i]]==0)leafs.push(v[i]);
		}
		for(int i=1;i<=n;i++){
			printf("%d:",i);
			sort(adj[i].begin(),adj[i].end());
			for(int j=0;j<adj[i].size();j++)
			printf(" %d",adj[i][j]);
			puts("");
		}
	}
}











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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值