算法与数据结构实验题 4.7 不知道取什么好

实验任务

有一个长度为 n 的序列,第 i 个数的大小为 a[i]。现在从第 1 个数开始从左往右进行以下操作:

  1. 如果当前数是剩下的数中最大的,则输出并删去这个数。

  2. 若不是,将它放到序列的末尾。

现在,bg 想知道一开始的第 m(从 1 开始计数)个数第几次被输出。

数据输入

第一行输入两个正整数 n(0<n<=1000)、m(1=<m<=n)。

接下去一行有 n 个正整数,第 i 个数表示 a[i]的值。

数据输出

输出一个数,表示第 m 个数第几次被输出。

输入示例

5 2
1 2 3 4 5

输出示例

4

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=2e9+1;

int T=1,n,m,a[1010],ans;
queue<pair<int,int>>que;

int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++) {
		scanf("%d",&a[i]);
		que.push({a[i],i});
	}
	sort(a+1,a+n+1);
	int out=n;
	while(1) {
		if(que.front().first==a[out]) {
			if(que.front().second==m) break;
			out--;
			ans++;
			que.pop();
		}
		else {
			que.push(que.front());
			que.pop();
		}
	}
	printf("%d",ans+1);
	return 0;
}

思路
又一道模拟
只要将初始队列存好,把最大的数放在另一个数组内排好,用i来判断当前队首是否为最大,按题意模拟即可

posted @ 2024-11-25 23:02  Severj  阅读(247)  评论(0)    收藏  举报