光荣的梦想(分治)

描述

Prince对他在这片大陆上维护的秩序感到满意,于是决定启程离开艾泽拉斯。在他动身之前,Prince决定赋予King_Bette最强大的能量以守护世界、保卫这里的平衡与和谐。在那个时代,平衡是个梦想。因为有很多奇异的物种拥有各种不稳定的能量,平衡瞬间即被打破。KB决定求助于你,帮助他完成这个梦想。

一串数列即表示一个世界的状态。

平衡是指这串数列以升序排列。而从一串无序数列到有序数列需要通过交换数列中的元素来实现。KB的能量只能交换相邻两个数字。他想知道他最少需要交换几次就能使数列有序。

格式

输入格式

第一行为数列中数的个数n,第二行为n ≤ 10000个数。表示当前数列的状态。

输出格式

输出一个整数,表示最少需要交换几次能达到平衡状态。

样例

输入样例

4
2 1 4 3

输出样例

2

限制

时间限制: 1000 ms

内存限制: 65536 KB

#include <bits/stdc++.h> 
using namespace std;

int ans=0, tmp=0;
int a[10005];
void recursive(int);

int main()
{
    int n;
    scanf ("%d", &n);
	for (int i=0; i<n; i++) {
		scanf ("%d", &a[i]);
	} 
	for (int i=0; i<n; i++)
		recursive(n);
	printf ("%d", ans);
    return 0;
}

void recursive(int n) {
	if (n == 1) {
		return ;
	}
	if (a[n-1] < a[n-2]) {
		ans++;
		tmp = a[n-1];
		a[n-1] = a[n-2];
		a[n-2] = tmp;
	}
	recursive(n-1);
}
发布了89 篇原创文章 · 获赞 77 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/wodemaoheise/article/details/105104025
今日推荐