HDU 5122 K.Bro Sorting

【题目大意】

    给定一个长度为n的序列,每次可以选一个数做以下操作:

    1.不断把这个数和它右边的数交换。

    2.当它右边没有数或者右边的数比它大时,停止操作。

    比如序列:1 4 3 2 5对4操作后序列为1 3 2 4 5。

    求最少要几次操作,使得这个序列变成升序。

【输入格式】

    第一行读入数据组数T。

    每组数据第一行为n,第二行为n个数,从左到右描述给定序列。

【输出格式】

    每组数据输出Case #x: y;x表示数据组数,y表示答案,即最少操作次数。

【样例输入】

2

5

5 4 3 2 1

5

5 1 2 3 4

样例输出

Case #1: 4

Case #2: 1


    由题意可以知道,一个操作只能让一个数向右移,那么如果存在一对数a[ i ] > a[ j ],那么一定会对a[ i ]进行一次操作,所以可以用O(n)的复杂度统计这种数的个数,即从小到大枚举,维护最右边的已出现过的数。

    考虑从小到大操作,当一个数不用移动时就不操作,否则就操作,这样,对于每个需要操作的数,只用进行一次操作,复杂度即为O(n)。

    贴代码:

#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e6+1;
int Read()
{
	int i=0,f=1;
	char c;
	for(c=getchar();(c>'9'||c<'0')&&c!='-';c=getchar());
	if(c=='-')
	  f=-1,c=getchar();
	for(;c>='0'&&c<='9';c=getchar())
	  i=(i<<3)+(i<<1)+c-'0';
	return i*f;
}

int n,a[MAXN];
int main()
{
	int T;
	T=Read();
	int sum=0;
	while(T--)
	{
		sum++;
		n=Read();
		for(int i=1;i<=n;i++)
		  a[i]=Read();
		int c=a[n],tot=0;
		for(int i=n-1;i>0;i--)
			if(a[i]>c)
			  tot++;
			else 
			  c=a[i];
		printf("Case #%d: %d\n",sum,tot);
	}
}

猜你喜欢

转载自blog.csdn.net/g21glf/article/details/80985822
今日推荐