hdu6215 Brute Force Sorting

地址:http://acm.split.hdu.edu.cn/showproblem.php?pid=6215

题目:

Brute Force Sorting

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 496    Accepted Submission(s): 119

Problem Description
Beerus needs to sort an array of N 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] of the array is sorted if it satisfies the following requirements.
1. A[i] is the first element of the array, or it is no smaller than the left one A[i−1].
2. A[i] is the last element of the array, or it is no bigger than the right one A[i+1].
In [1,4,5,2,3], for instance, the element 5 and the element 2 would be destoryed by Beerus. The array would become [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) 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 100000.
The second line describes the array with N positive integers A[1],A[2],⋯,A[N] where each integer A[i] satisfies 1≤A[i]≤100000.
 
Output
For eact test case output two lines.
The first line contains an integer M which is the size of the final array.
The second line contains M integers describing the final array.
If the final array is empty, M should be 0 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

 
Source
 
思路:
  直接模拟多次扫数组肯定不行,TLE。
  仔细观察后发现在删一个数后v[i],在下一次的扫描中只会影响v[i]的前一个数和后一个数,所以我们可以用双向链表做。
  每次把被影响的数保存起来,然后从这些数开始扫,用链表模拟删除操作,把删除数的前一个数留到下次扫描。
  因为被删除的数最多只有n个,所以时间复杂度O(n)。
  我因为用了set来去重,时间复杂度变成了O(nlogn),不过也可以不用set,我只是为了好写。
 #include <bits/stdc++.h>

 using namespace std;

 #define MP make_pair
#define PB push_back
typedef long long LL;
typedef pair<int,int> PII;
const double eps=1e-;
const double pi=acos(-1.0);
const int K=1e6+;
const int mod=1e9+; int now,pre,v[K],pe[K],nt[K],dl[K];
set<int>st;
vector<int>tmp; int main(void)
{
//freopen("in.acm","r",stdin);
int t,n;cin>>t;
while(t--)
{
memset(dl,,sizeof dl);
scanf("%d",&n);
for(int i=;i<=n;i++) dl[i]=,scanf("%d",v+i),pe[i]=i-,nt[i]=i+,st.insert(i);
nt[]=,pe[n+]=n,pe[]=,nt[n]=n+;
v[]=,v[n+]=K;
while(st.size())
{
tmp.clear();
for(auto &x:st)
{
int ntx=nt[x],px=pe[x];
if(v[px]>v[x]) tmp.PB(px),tmp.PB(x);
if(v[x]>v[ntx]) tmp.PB(x),tmp.PB(ntx);
}
st.clear();
for(auto &x:tmp)
if(!dl[x])
{
int ntx=nt[x],px=pe[x];
nt[px]=ntx,pe[ntx]=px;
st.insert(px);
dl[x]=;
}
}
int cnt=;
for(int i=nt[];i!=n+;i=nt[i]) cnt++;
printf("%d\n",cnt);
for(int i=nt[];i!=n+;i=nt[i]) printf("%d ",v[i]);
printf("\n");
}
return ;
}
上一篇:Linux查看磁盘空间大小


下一篇:HDU 5642 King's Order 动态规划