hdu 6215 链表

来源:互联网 发布:淘宝卖衣服代理兼职 编辑:程序博客网 时间:2024/06/06 08:47

Beerus needs to sort an array of NN integers. Algorithms are not Beerus’s strength. Destruction is what he excels. He can destroy all unsorted numbers in the array simultaneously. A number A[i]A[i] of the array is sorted if it satisfies the following requirements.
1. A[i]A[i] is the first element of the array, or it is no smaller than the left one A[i−1]A[i−1].
2. A[i]A[i] is the last element of the array, or it is no bigger than the right one A[i+1]A[i+1].
In [1,4,5,2,3][1,4,5,2,3], for instance, the element 55 and the element 22 would be destoryed by Beerus. The array would become [1,4,3][1,4,3]. If the new array were still unsorted, Beerus would do it again.
Help Beerus predict the final array.
Input
The first line of input contains an integer T (1≤T≤10)T (1≤T≤10) which is the total number of test cases.
For each test case, the first line provides the size of the inital array which would be positive and no bigger than 100000100000.
The second line describes the array with NN positive integers A[1],A[2],⋯,A[N]A[1],A[2],⋯,A[N] where each integer A[i]A[i] satisfies 1≤A[i]≤1000001≤A[i]≤100000.
Output
For eact test case output two lines.
The first line contains an integer MM which is the size of the final array.
The second line contains MM integers describing the final array.
If the final array is empty, MM should be 00 and the second line should be an empty line.
Sample Input
5
5
1 2 3 4 5
5
5 4 3 2 1
5
1 2 3 2 1
5
1 3 5 4 2
5
2 4 1 3 5
Sample Output
5
1 2 3 4 5
0

2
1 2
2
1 3
3
2 3 5

。。很久都没看懂题意,原来以为是不满足的两个删去,原来是每一层只要是不满足 a[i]<=a[i+1]的都要删去。醉了,醉了
暴力枚举链表就行,放进一个队列里面,每次删去后,把前继进队重新判。。。

#include <bits/stdc++.h>using namespace std;const int N = 1e5+10;int last[N],nxt[N],que[N],a[N];int main(){    int t;    scanf("%d",&t);    while(t--)    {        int n;        scanf("%d",&n);        a[0]=0;        nxt[0]=1;        last[n+1]=n;        int top=0;        for(int i=1;i<=n;i++)        {            scanf("%d",&a[i]);            last[i]=i-1;            nxt[i]=i+1;            que[top++]=i;        }        int ans=n;        int flag=1;        while(flag)        {            flag=0;            int now=0;            int s=0;            while(now<top)            {                int i=que[now];                int ff=0;                while(nxt[i]<=n)                {                    if(a[i]>a[nxt[i]]) ff++,flag=1,i=nxt[i];                    else break;                }                if(ff) ans-=(ff+1);                if(ff)                {                    nxt[last[que[now]]]=nxt[i];                    last[nxt[i]]=last[que[now]];                    que[s++]=last[que[now]];                }                while(que[now]<=i&&now<top) now++;            }            top=s;        }        printf("%d\n",ans );        int now=0;        while(now<=n)        {            if(now!=0) printf("%d ",a[now] );            now=nxt[now];        }        printf("\n");    }}
原创粉丝点击