当前位置:编程学习 > C/C++ >>

PAT1053-Path of Equal Weight

读题不认真,纠结了半天: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语言源码:
[cpp]  
#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);*/  
    }  www.zzzyk.com
    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;  
}  
 
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,