PAT (Advanced Level) 1052. Linked List Sorting (25)

简单题。

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<map>
#include<queue>
#include<string>
#include<stack>
#include<vector>
using namespace std;

const int maxn=100000+10;
int n,h;
struct X
{
    int a,b,c;
} node[maxn],p[maxn];
int f[maxn];

bool cmp(const X&a,const X&b)
{
    return a.b<b.b;
}

int main()
{
    memset(f,0,sizeof f);
    scanf("%d%d",&n,&h);

    for(int i=1; i<=n; i++)
    {
        scanf("%d%d%d",&node[i].a,&node[i].b,&node[i].c);
        f[node[i].a]=i;
    }

    if(h==-1)printf("0 -1
");
    else
    {
        int now=f[h];
        int x=0;
        while(1)
        {
            p[x++]=node[now];
            if(node[now].c==-1) break;
            now=f[node[now].c];
        }

        if(x==0)
        {
            if(h==-1) printf("0 -1
");
            else printf("0 %05d
",h);
        }

        else
        {
            sort(p,p+x,cmp);
            h=p[0].a;
            printf("%d %05d
",x,h);
            for(int i=0; i<x; i++)
            {
                if(i<x-1) printf("%05d %d %05d
",p[i].a,p[i].b,p[i+1].a);
                else printf("%05d %d -1
",p[i].a,p[i].b);
            }
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zufezzt/p/5527912.html