算法與數據結構實驗題 4.3 不知道取什么好


1、題目:

2、代碼:

#include<iostream>
#include<algorithm>
using namespace std;
//以這組數據為例說明:10 2
//1 4 7 4 9 6 5 9 8 4
int main()
{
	int n,m;
	cin>>n>>m;
	m=m-1;
	int i,j=0;
	int a[1001],b[1001],c[1001];
	for(i=0; i<n; i++)
	{
		cin>>a[i];
		b[i]=a[i];
		c[i]=a[i];
	}
	sort(b,b+n);//找出最大值
	int count;
	//找到第一個最大值所在位置
	for(i=0; i<n; i++)
	{
		if(a[i]==b[n-1])
		{
			count=i;
			break;
		}
	}
	//對數組a進行第一次重新排列,變成 9 6 5 9 8 4 1 4 7 4
	int num=count;
	for(i=0; i<n; i++)
	{
		if(i<n-num)
		{
			a[i]=c[count];
			count++;
		}
		else
		{
			a[i]=c[j];
			j++;
		}
	}

	int k;
	if(m<num)
	{
		k=n-num+m;//此時我們原來的第二個數據變成了現在數組中的a[7];
	}
	else
	{
		k=m-num;
	}
	int count1=0,count2=0,count3;
	//重新排列之后,計算在所要輸出的數字前后比它大的數有多少
	for(i=0; i<k; i++)
	{
		if(a[i]>=a[k])
		{
			count1++;//在要求輸出的數之前的與之相等的數一定比它先輸出
		}
	}
	for(i=k+1; i<n; i++)
	{
		if(a[i]>a[k])
		{
			count2++;//比它大的數一定先輸出
		}
		if(a[i]==a[k])
		{
			count3++;
		}
	}
	//如果在要求輸出的數之前比它大的數的個數大於之后的個數時,
	//之后序列里的與之相等的數一定不會輸出,反之則一定輸出
	//比如,若要求輸出7后面的4,則8后面的4一定先比7后的4先輸出
	if(count1<=count2)
	{
		cout<<count1+count2+count3+1<<endl;
	}
	else
	{
		cout<<count1+count2+1<<endl;
	}

	return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM