题目给一棵树,是一棵多叉树,而且根结点还是不确定的!刚开始真没头绪,做是可以做,不过实在太麻烦。
后来终于发现,其实完全可以把题目给的树看成一个无向图!所谓的叶子结点,其实就是度为1的点。只要用邻接矩阵表示这个图,找出度为1且编号最小的点:先输出与其相邻的点再删除掉。不断重复这个过程直到结点数量为1。
因为数据规模很小所以成绩还不错的,空间方面如果改成用bit位保存邻接矩阵的话应该能做的更好。
注意:输入的数字可能不只一位的(所以我没有用%s)!
Accepted | 1097 | C++ | 00:00.00 | 396K |
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
void solve(char tree[][51],int cnt)
{
int max = cnt;
for(int i = 1; i <= cnt && max > 1; i++ )
{
int temp,flag = 0 ;
for(int j = 1; j <= cnt; j++ )
if(tree[i][j] == 1 )
{
flag++ ;
temp = j;
}
if(flag == 1 )
{
printf("%d" ,temp);
if(--max > 1 )
printf(" " );
tree[i][temp] = 0 ;
tree[temp][i] = 0 ;
if(temp < i) i = temp - 1 ;
}
}
printf("/n" );
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1097.txt","r" ,stdin);
#endif
char tree[51][51 ];
memset(tree,0,sizeof (tree));
int stack[100],top = 0 ;
char ch;
int cnt = 0 ;
while(scanf("%*[ /n/t]") != EOF && scanf("%c",&ch) != EOF)
{//第一个scanf用于过滤空白符
if(ch == '(' )
{
scanf("%d",&stack[top++ ]);
cnt++ ;
}
else if(ch == ')' )
{
top-- ;
if(top > 0 )
{
tree[stack[top]][stack[top - 1]] = 1 ;
tree[stack[top - 1]][stack[top]] = 1 ;
}
}
if(top == 0 )
{
solve(tree,cnt);
cnt = 0 ;
top = 0 ;
}
}
#ifndef ONLINE_JUDGE
fclose(stdin);
#endif
return 0 ;
}
#include <string.h>
#include <stdlib.h>
void solve(char tree[][51],int cnt)
{
int max = cnt;
for(int i = 1; i <= cnt && max > 1; i++ )
{
int temp,flag = 0 ;
for(int j = 1; j <= cnt; j++ )
if(tree[i][j] == 1 )
{
flag++ ;
temp = j;
}
if(flag == 1 )
{
printf("%d" ,temp);
if(--max > 1 )
printf(" " );
tree[i][temp] = 0 ;
tree[temp][i] = 0 ;
if(temp < i) i = temp - 1 ;
}
}
printf("/n" );
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1097.txt","r" ,stdin);
#endif
char tree[51][51 ];
memset(tree,0,sizeof (tree));
int stack[100],top = 0 ;
char ch;
int cnt = 0 ;
while(scanf("%*[ /n/t]") != EOF && scanf("%c",&ch) != EOF)
{//第一个scanf用于过滤空白符
if(ch == '(' )
{
scanf("%d",&stack[top++ ]);
cnt++ ;
}
else if(ch == ')' )
{
top-- ;
if(top > 0 )
{
tree[stack[top]][stack[top - 1]] = 1 ;
tree[stack[top - 1]][stack[top]] = 1 ;
}
}
if(top == 0 )
{
solve(tree,cnt);
cnt = 0 ;
top = 0 ;
}
}
#ifndef ONLINE_JUDGE
fclose(stdin);
#endif
return 0 ;
}