problem 1097
来源:互联网 发布:开淘宝店规则 编辑:程序博客网 时间:2024/06/06 17:16
题目给一棵树,是一棵多叉树,而且根结点还是不确定的!刚开始真没头绪,做是可以做,不过实在太麻烦。
后来终于发现,其实完全可以把题目给的树看成一个无向图!所谓的叶子结点,其实就是度为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;
}
- problem 1097
- problem
- Problem
- problem
- Problem
- Problem
- Problem
- Problem
- Problem
- Problem
- problem
- Problem
- Problem
- Problem
- Problem
- Problem
- Problem
- Problem
- 哈佛图书馆自习室墙上的训言
- ASP.net(c#)单元格中用"..."替换超长字符
- TCP/IP子网教程
- http://www.cnblogs.com/matrix
- 串口调试精灵的使用和串口程序调试技巧
- problem 1097
- speedtree的延伸
- 在嵌入式Linux 系统中实现基于Web 的配置管理
- 图文并茂教您配置Exchange Server 2003
- asp.net(c#)中文验证码程序
- [转]国内优秀论坛之大汇集
- 追寻可可西里
- 昨天家里被盗了
- 冰火两重天 e-HR给传媒业带来了啥?