从前往后扫,找到一出现次数为0的数,从后面找一个出现不为0的数转化而来。设置两指针l, r来处理。
#include<cstdio> #include<iostream> #include<cstdlib> #include<cstring> #include<string> #include<algorithm> #include<map> #include<queue> #include<vector> #include<cmath> #include<utility> using namespace std; typedef long long LL; const int N = 1000008, INF = 0x3F3F3F3F; int a[N], cnt[N], rem[N]; int main(){ int n, s; cin >> n >> s; for(int i = 1; i <= n; i++){ scanf("%d", &a[i]); } int ans = 0; if(a[s]){ ans++; a[s] = 0; } for(int i = 1; i <= n; i++){ cnt[a[i]]++; } cnt[n] += cnt[0] - 1; int l = 1, r = n; while(l < r){ while(cnt[l] && l < r){ l++; } while(cnt[r] == 0 && l < r){ r--; } if(l < r){ cnt[l]++; cnt[r]--; ans++; } } cout<<ans<<endl; return 0; }
时间: 2024-10-08 01:53:07