PAT甲1052 Linked List Sorting (25)(25 分)

尝试选择排序,超时了;
直接插入正常。

#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <string>
using namespace std;

struct node
{
    int now;
    int next;
    int data;
    node()
    {
        next=-1;
        data=0;
    }
}A[100010];

int N,st;

int main()
{
    scanf("%d%d",&N,&st);
    int now,next,data;
    for(int i=0;i<N;i++)
    {
        scanf("%d%d%d",&now,&data,&next);
        A[now].now=now;
        A[now].data=data;
        A[now].next=next;
    }
    int rh=100005;
    A[rh].next=-1;
    int p=st;
    int r;
    int pre=rh;
    int num=0;
    while(p!=-1)
    {
        pre=rh;
        while(A[pre].next!=-1&&A[A[pre].next].data<A[p].data)
        {
            pre=A[pre].next;
        }
        r=A[p].next;
        A[p].next=A[pre].next;
        A[pre].next=p;
        p=r;
        num++;
    }
    p=A[rh].next;
    if(num>0)
    {
        printf("%d %05d\n",num,p);
    }
    else
    {
        printf("0 -1\n",0);
    }

    while(p!=-1)
    {
        if(A[p].next!=-1)
        {
            printf("%05d %d %05d\n",A[p].now,A[p].data,A[p].next);
        }
        else
        {
            printf("%05d %d %d\n",A[p].now,A[p].data,A[p].next);
        }
        p=A[p].next;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yhy489275918/article/details/81842448