跳到正文

算法·理论

U561591 题解

Leo_hele约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年5月10日
收录
2026年8月5日
更新
2026年11月16日
篇幅
约 4 分钟
获赞
1

版本

  1. v1当前

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

题目:纸牌神庙

70分做法

思路

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

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


代码

C++
#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;
}

正解

思路

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

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

所以可以建一个表示cntscnt_s的map,储存si=xs_i=x的个数。

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


代码

C++
#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;
}

比真正枚举还简单……

原文