Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

PAT1053-Path of Equal Weight

$
0
0

题目地址:http://pat.zju.edu.cn/contests/pat-a-practise/1053

读题不认真,纠结了半天:Each path occupies a line with printed weights from the root to the leaf in order

其实针对最后输出排序:

将路径(int)Stack[n]保存到(char)S[i]中,按字符串对S[i]进行排序,就能得到符合要求的输出结果了。

C语言源码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct child
{
	int num;
	int w;
}child;
typedef struct node
{
	int w;
	int top;
	child c[200];
}node;
node A[200];
int cmp(const void *a,const void *b)
{
	child *aa=(child *)a;
	child *bb=(child *)b;
	return bb->w-aa->w;
}
int cmp1(const void *a,const void *b)
{
	return strcmp((char *)b,(char *)a);
}
int Stack[200],top,sum,s;
char S[200][200];
int tops[200],nu;
void dfs(int k)
{
	int i;
	sum+=A[k].w;
	Stack[top++]=A[k].w;
	if(A[k].top==0)
	{
		if(sum==s)
		{
			tops[nu]=top;
			for(i=0;i<top;i++)
				S[nu][i]=Stack[i];
			S[nu][i]='\0';
			nu++;
		}
	}
	else
		for(i=0;i<A[k].top;i++)
			dfs(A[k].c[i].num);
	sum-=A[k].w;
	top--;
}
int main()
{
	int n,m,i,num,j,x;
	scanf("%d %d %d",&n,&m,&s);
	for(i=0;i<200;i++)
	{
		A[i].top=0;
		tops[i]=0;
	}
	for(i=0;i<n;i++)
		scanf("%d",&A[i].w);
	for(i=0;i<m;i++)
	{
		scanf("%d",&num);
		scanf("%d",&A[num].top);
		for(j=0;j<A[num].top;j++)
		{
			scanf("%d",&x);
			A[num].c[j].num=x;
			A[num].c[j].w=A[x].w;
		}
		/*qsort(A[num].c,A[num].top,sizeof(A[num].c[0]),cmp);*/
	}
	top=0;sum=0;nu=0;
	dfs(0);
	qsort(S,nu,sizeof(S[0]),cmp1);
	for(i=0;i<nu;i++)
	{
		for(j=0;j<(int)strlen(S[i])-1;j++)
			printf("%d ",S[i][j]);
		printf("%d\n",S[i][j]);
	}
	return 0;
}


作者:leizh007 发表于2013-3-14 8:19:20 原文链接
阅读:0 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>