U561591 题解

· · 算法·理论

注:此文章为下面题目的题解,因为只能关联公开题目,所以没有设定为题解。

题目:纸牌神庙

70分做法

思路

按照题目所说,枚举断点,对于每个断点,用贪心尝试一遍,最后取最小值。

尝试方法:令m为最后每堆牌的数量,如果 a_{i}\not= m,则令a_i-m\rightarrow^{+} a_{i+1}\text{ret}=\text{ret}+1

代码

#include<bits/stdc++.h>
#define _fo(i, l, cod, s, ...) for (int i = l; cod; i += s)
#define fo(...) _fo(__VA_ARGS__, 1)
#define _up(i, l, r, s, ...) _fo(i, l, i <= r, s)
#define up(...) _up(__VA_ARGS__, 1)
#define _dn(i, r, l, s, ...) _fo (i, r, i >= l, -(s))
#define dn(...) _dn(__VA_ARGS__, 1)
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int N = 1e5+5;
int n;
int a[N], b[N];
int main(){
    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> n;
    int num = 0;
    up (i, 1, n) cin >> a[i], num += a[i];
    if (num % n) return cout << -1, 0; //特判-1
    num /= n;
    int ans = INT_MAX;
    up (i, 1, n){ //枚举断点
        memcpy(b, a, sizeof b);
        int ret = 0;
        up (j, i+1, n){
            if (b[j] != num)
                b[j%n+1] += b[j] - num, b[j] = num, ret++;
        }
        up (j, 1, i-1){
            if (b[j] != num)
                b[j+1] += b[j] - num, b[j] = num, ret++;
        }
        if (b[i] != num) continue; //不成功
        ans = min(ans, ret);
    }
    cout << ans;
    return 0;
}

正解

思路

考虑什么时候不用把牌转移到下一个呢?

答案是在个数恰好为m时,也就是前缀和s_j-s_{i-1}=0时(注:前缀和s_i=s_{i-1}+a_i-m),因为每个都满足,无需转移纸牌。

所以可以建一个表示cnt_s的map,储存s_i=x的个数。

当枚举断点时,\text{ret}为n-cnt_{s_i},有cnt_{s_i}个不用转移。 如果不用转移的点到n后面(也就是回到了1),也不需要特判,因为根据m的定义可知s_{n}=0

代码

#include<bits/stdc++.h>
#define _fo(i, l, cod, s, ...) for (int i = l; cod; i += s)
#define fo(...) _fo(__VA_ARGS__, 1)
#define _up(i, l, r, s, ...) _fo(i, l, i <= r, s)
#define up(...) _up(__VA_ARGS__, 1)
#define _dn(i, r, l, s, ...) _fo (i, r, i >= l, -(s))
#define dn(...) _dn(__VA_ARGS__, 1)
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int N = 1e5+5;
int n;
int a[N], s[N]; 
unordered_map<int, int> mp;
int main(){
    cin >> n;
    int num = 0;
    up (i, 1, n) cin >> a[i], num += a[i];
    if (num % n) return cout << -1 , 0;
    num /= n;
    up (i, 1, n) s[i] = s[i-1] + a[i] - num, mp[s[i]]++;
    int ans = 0;
    for (auto p: mp){
        ans = max(ans, p.second);
    }
    cout << n-ans;

    return 0;
}

比真正枚举还简单……