0%

HDU 5933 ArcSoft's Office Rearrangement 题解

HDU 5933 ArcSoft's Office Rearrangement 题解

题目大意

\(n\) 个石子堆,要求可以任意把某一堆分成两半,或把两个堆合并,问最少需要多少次操作使石子堆变成每堆相等的 \(k\) 堆。

题解

模拟,我们想象最终状态,每个石子堆都是由相邻的两边的原始石子堆拆分与合并而成,于是我们从左到右模拟这个过程即可,代码实现要注意很多细节(WA了无数次)。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//https://acm.hdu.edu.cn/showproblem.php?pid=5933
#include <cstdio>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cassert>
#include <cmath>
using namespace std;
typedef long long ll;

template <typename _Tp>
void read(_Tp &a, char c = 0, int f = 1) {
for(c = getchar(); !isdigit(c); c = getchar()) if(c == '-') f = -1;
for(a = 0; isdigit(c); a = a * 10 + c - '0', c = getchar()); a *= f;
}

template <typename _Tp>
void write(_Tp a) {
if(a < 0) putchar('-'), a = -a;
if(a > 9) write(a / 10); putchar(a % 10 + '0');
}

const int N = 1e5 + 5;

ll n, k;
ll a[N];

int main() {
// freopen("0723_2.in", "r", stdin);
int T;
read(T);
for(int _T = 1; _T <= T; _T++) {
read(n), read(k);
ll s = 0;
for(int i = 1; i <= n; i++) {
read(a[i]);
s += a[i];
}
ll t = -1, ans = - 1;
if(s % k == 0) {
t = s / k;
ans = 0;
ll lst = 0;
for(int i = 1; i <= n; i++) {
if(lst + a[i] > t) {
if(lst) ans++;
ans++;
a[i] -= t - lst;
lst = 0;
while(a[i] >= t) {
a[i] -= t;
ans++;
}
if(a[i] == 0) ans--;
lst = a[i];
a[i] = 0;
} else if(lst + a[i] == t) {
if(lst) ans++;
lst = 0;
a[i] = 0;
} else {
if(lst) ans++;
lst += a[i];
a[i] = 0;
}
// for(int i = 1; i <= n; i++) printf("%d ", a[i]); puts("");
}
} else {
ans = -1;
}
printf("Case #%d: %lld\n", _T, ans);
}
return 0;
}