CodeForces - 144A-day-3-A

问题来源

CodeForces - 144A

问题描述

A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.

By the military charter the soldiers should stand in the order of non-increasing of their height. But as there’s virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.

For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.

Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

输入

The first input line contains the only integer n (2 ≤ n ≤ 100) which represents the number of soldiers in the line. The second line contains integers a1, a2, …, an (1 ≤ ai ≤ 100) the values of the soldiers’ heights in the order of soldiers’ heights’ increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1, a2, …, an are not necessarily different.

输出

Print the only integer — the minimum number of seconds the colonel will need to form a line-up the general will like.

例子在这里插入图片描述

AC的代码

#include<string>
#include <iostream>
using namespace std;
int main()
{
	int aa[101],i;
	cin >> i;
	for (int g = 0; g < i; g++)
	{
		cin >> aa[g];
	}
	int min=1000, max=0,min1,max1;
	for (int f = 0; f < i; f++)
	{
		if (aa[f] <= min)
		{
			min = aa[f];
			min1 = f;
		}
		if (aa[f] > max)
		{
			max = aa[f];
			max1 = f;
		}
	}
	if (min1 < max1)
	{
		cout << i - 2 - min1 + max1 << endl;
	}
	else
	{
		cout << i - 1 - min1 + max1 << endl;
	}



}

解题思路

最高的人到最左边,最矮的到最右边,分成两种情况。
(1)最高的人不需要跨过最矮的人.。
(2)最高的人要跨过最矮的人。
第一种情况:
最高的人到最左边,最矮的人到最右边互不干扰。
步数和为i - 1 - min1 + max1。
第二种情况:
假定最高的人先走,他经过的时候,和最矮的人换位,那最矮的人需要的步减一。
步数和为i - 2 - min1 + max1。

猜你喜欢

转载自blog.csdn.net/weixin_43957652/article/details/86623332