U561591 题解
注:此文章为下面题目的题解,因为只能关联公开题目,所以没有设定为题解。
题目:纸牌神庙
70分做法
思路
按照题目所说,枚举断点,对于每个断点,用贪心尝试一遍,最后取最小值。
尝试方法:令
代码
#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;
}
正解
思路
考虑什么时候不用把牌转移到下一个呢?
答案是在个数恰好为
所以可以建一个表示map,储存
当枚举断点时,
代码
#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;
}
比真正枚举还简单……