a712困難週期最小值分組與完整週期停止證明
CPE:Eat or not to Eat? (UVa 10273)
正確辨認永不再吃牛的時刻,同時避免逐日掃描所有牛。
解題思路
所有週期Ti≤10,整體產量序列在L=lcm(Ti)≤2520天後重複。只要連續L天沒有吃牛,存活集合未變且所有相位都看過,未來也永遠不會再吃;每吃一頭就把連續無事件天數歸0。不能只模擬總共2520天,因為中途刪牛會改變之後的最小值與平手情況。
為每種週期t、相位p、產量v維護存活牛數與牛編號XOR,並維護該相位的最小非空v。每天只需查至多10種週期在day%t的最小值,合併全域最小值的牛數;恰一頭時用XOR取回編號。刪牛時只更新牠所屬週期的至多10個相位,空桶使最小指標向上移。日序從0計算相位,輸出日期要加1;從未刪除時最後日期為0。
Step-by-step animation
示意:牛1週期[1,3],牛2、3皆週期[2]
步驟 1 / 3
第1天
產量1,2,2,唯一最少是牛1,吃掉牠。
牛1:1
牛2:2
牛3:2
- 存活
- 2
- 最後日期
- 1
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
struct Phase {
vector<int> count, ids;
int low;
Phase() : count(251), ids(251), low(251) {}
};
int main() {
int tests;
cin >> tests;
while (tests--) {
int n;
cin >> n;
vector<vector<int>> cows(n + 1);
vector<vector<Phase>> group(11);
for (int t = 1; t <= 10; t++)
group[t].resize(t);
vector<int> periods;
bool exists[11] = {};
int cycle = 1;
for (int id = 1; id <= n; id++) {
int t;
cin >> t;
cows[id].resize(t);
exists[t] = true;
cycle = lcm(cycle, t);
for (int p = 0; p < t; p++) {
int v;
cin >> v;
cows[id][p] = v;
auto &b = group[t][p];
b.count[v]++;
b.ids[v] ^= id;
if (v < b.low)
b.low = v;
}
}
for (int t = 1; t <= 10; t++)
if (exists[t])
periods.push_back(t);
int alive = n, last = 0, quiet = 0, day = 0;
while (alive && quiet < cycle) {
int minimum = 251, count = 0, id = 0;
for (int t : periods) {
auto &b = group[t][day % t];
int v = b.low;
if (v == 251)
continue;
if (v < minimum) {
minimum = v;
count = b.count[v];
id = b.ids[v];
} else if (v == minimum) {
count += b.count[v];
id ^= b.ids[v];
}
}
if (count == 1) {
alive--;
last = day + 1;
quiet = 0;
int t = cows[id].size();
for (int p = 0; p < t; p++) {
int v = cows[id][p];
auto &b = group[t][p];
b.count[v]--;
b.ids[v] ^= id;
while (b.low < 251 && b.count[b.low] == 0)
b.low++;
}
} else
quiet++;
day++;
}
cout << alive << ' ' << last << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。