Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) Total Submission(s): 1823 Accepted Submission(s): 938 Problem Description dxy has a collection of a series of books called "The Stories of SDOI",There are n(n≤19) books in this series.Every book has a number from 1 to n .
Input There are several testcases.
Output For each testcase,output one line for an integer standing for the minimum steps Evensgn would use to reorder the books.
Sample Input 2 4 4 1 2 3 5 1 2 3 4 5
Sample Output 3 0
Source
Recommend hujie
|
题目大意:有N本书,现在这N本书是无序的,你可以从中间拿出一本放到最顶,问最少拿几次可以吧这个无序的书重新整理好,书的编号为从1-N
思路:首先大体的思路是这样的,如果某个数比如5,在他的后面有4,那么这个时候你就要至少拿一次把书拿到5的前面,
实现的时候,我们可以用一个数组保存一个数的位置,最后查找的时候从大数向小数查找,因为书的序号是从1-n的,经过排序的书就不需要再次排序了,所以直接将她的位置弄成0就可以了,注意一些细节很快就做出来吧。
代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[25];
int index[25];
int main()
{
int t,n,ans;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
index[a[i]]=i;
}
ans=0;
for(int i=n;i>=1;i--)
{
int v=i-1; //往后判断某个书的前一个书是否在他的后面
for(int j=index[i]+1;j<=n;j++)
{
if(a[j]==v)
{
ans++;
index[a[j]]=0;
break;
}
}
}
printf("%d\n",ans);
}
return 0;
}