CF C. Sort Zero

位置:Problem - C - Codeforces

You are given an array of nn positive integers a1,a2,…,an

In one operation you do the following:

  1. Choose any integer x.
  2. For all ii such that ai=x, do ai=0 (assign 0 to ai).

Find the minimum number of operations required tsio sort the array in non-decreasing order.

思路:

因为你能进行的操作是把某个数出现的位置上全变成零,所以这个数最后出现的位置往前的所有位置必须都变成零。因此,我们从后往前找到第一个a[i]<a[i-1]的位置,从i-1往前的位置都必须是零,但这个操作可能会让后面的某个或几个数变成零,所以找到最靠后的变成零的位置,此位置往前都变成零就可以了。

#include<bits/stdc++.h>
using namespace std;
int a[100010],f[100010];
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int n,temp=-1;
		cin>>n;
		map<int,int> mp;
		for(int i=0;i<n;i++)
		{
			cin>>a[i];
			f[a[i]]=0;
			mp[a[i]]=max(mp[a[i]],i);
		}
		if(n==1){cout<<0<<'\n';continue;
		}
		for(int i=n-1;i>=1;i--)
		{
			if(a[i]<a[i-1])
			{
				temp=i-1;break;
			}
		}
		if(temp==-1){cout<<0<<'\n';continue;
		}
		int maxx=-1,ans=0;
		for(int i=0;i<=temp;i++)
		{
			maxx=max(maxx,mp[a[i]]);
		}
		for(int i=0;i<=maxx;i++)//此位置(即maxx)往前都要变成零 
		{
			if(a[i]&&f[a[i]]==0)
			{
				f[a[i]]=1;
				ans++;
			}
		}
		cout<<ans<<'\n';
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值