You are given an array of nn positive integers a1,a2,…,an
In one operation you do the following:
- Choose any integer x.
- 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;
}