一个树形图的所有节点已经用1,2,……n来标号。用Prufer法则来表示这样一棵树需要依据如下方法:有最小编号的叶结点将被除去。这个叶结点和它在图中与之相邻的边将会一起被除去,然后记下被除去边的另一个端点。在图上重复这个过程,直到图中只剩下一个节点(顺便说一句,剩下的肯定是编号为n的节点)。然后,你将得到一个长度为n-1的数组,这个数组便成为Prufer树。
你的任务是,对于一颗指定的树,计算并输出它的Prufer树的代码。树的形式语言由如下的方法构造:
T ::= "(" N S ")"
S ::= " "T S | empty
N ::= number
注意,对于以上的定义,这棵树的根是不确定的。任何一个顶点都有可能成为这棵树的根。通常,我们称这种树为“无根树”。
你的任务是,对于一颗指定的树,计算并输出它的Prufer树的代码。树的形式语言由如下的方法构造:
T ::= "(" N S ")"
S ::= " "T S | empty
N ::= number
注意,对于以上的定义,这棵树的根是不确定的。任何一个顶点都有可能成为这棵树的根。通常,我们称这种树为“无根树”。
Input
输入可能有多组测试数据。每一组数据占一行,来表示一棵树。输入将以EOF结尾,每棵树的n的范围为1<=n<=50。
Output
对于每组测试数据,输出一行数字,即其对应的Prufer树。每两个数字间要有空格,但行末不要有。
Sample Input
(2 (6 (7)) (3) (5 (1) (4)) (8)) (1 (2 (3))) (6 (1 (4)) (2 (3) (5)))
Sample Output
记忆化深搜的部分很棒,需要再学习。
#include<iostream>
#include<algorithm>
#include<string>
#include<map>
#include<vector>
#include<cmath>
#include<queue>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
#define ll long long
using namespace std;
int now,n;
int g[60][60],in[60];
int build(char* str){
int num;
while (now<strlen(str)){
if (str[now] <= '9' && str[now] >= '0'){
if (str[now+1] <= '9' && str[now+1] >= '0'){ //两位数
num=(str[now]-'0')*10+(str[now+1]-'0');
now+=2;
}
else{ //一位数
num=str[now]-'0';
now++;
}
n++;
continue;
}
if (str[now] == '('){
now++;
int i=build(str); //递归,记忆化深搜,找到与num相连的点
in[num]++; //度数+1
in[i]++;
g[num][i]=1; //num和i连边
g[i][num]=1;
}
else if (str[now] == ')'){
now++;
return num;
}
else if (str[now] == ' '){
now++;
continue;
}
}
}
int main(){
int i,j,k,d;
char str[2000];
while (gets(str)&&str!=""){
n=0;
memset(in,0,sizeof(in));
memset(g,0,sizeof(g));
now=0;
build(str);
if (n == 1){
printf("\n");
continue;
}
for (i=1; i<n-1; i++){ //最后的数组是从这个树中找出n-1个点
for (j=1; j<n; j++){ //编号从小到大
if (in[j] == 1){ //叶节点
in[j]=-1; //删掉这个点
for (k=1; k<=n; k++){
if (g[j][k] == 1 || g[k][j] == 1){ //找出它的父节点
g[j][k]=0;
g[k][j]=0;
in[k]--; //父节点度数-1
printf("%d ",k);
break;
}
}
break;
}
}
}
printf("%d\n",n);
}
}