C 序列最小化

题目地址:

https://ac.nowcoder.com/acm/contest/5556/C

基本思路:

我们知道这个序列是N个数的全排列,那么很明显要一直替换最小替换到所有数相等,就是所有数都换成1。所以我们肯定第一步要找到包含1的区间替换,然后再从这个区间左右两边,连着一个1然后往前后替换就是了,所以考虑遍历所有长度为k包含1的区间,然后计算每次的替换次数取最小就是了。

参考代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define int long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF 0x3f3f3f3f

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
  return neg * x;
}
inline void print(int x) {
  if (x < 0) { putchar('-'); x = -x; }
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}

const int maxn = 1e5 + 10;
int n,k,a[maxn];
signed main() {
  IO;
  cin >> n >> k;
  int tag = 0;
  rep(i,1,n){
   cin >> a[i];
   if(a[i] == 1) tag = i;//找到1的位置;
  }
  int ans = INF;
  for(int l = max(1LL,tag - k + 1); l <= tag ; l++){
    int r = min(n,l + k - 1);
    //这个区间左半部分要换几次;
    int k1 = (int)ceil((double)(l - 1) / (double)(k - 1));
    //这个区间右半部分要换几次;
    int k2 = (int)ceil((double(n - r) / (double)(k - 1)));
    int res = k1 + k2 + 1;
    ans = min(ans,res);
  }
  cout << ans << '\n';
  return 0;
}