题面
来源:USACO 官网。模型收到的是同一份题面的文字。
**Note: The time limit for this problem is 3s, 1.5x the default.**
Farmer John has $N$ ($2 \leq N \leq 2 \cdot 10^5$) cows numbered from $1$ to $N$. An election is being held in FJ's farm to determine the two new head cows in his farm. Initially, it is known that cow $i$ will vote for cow $a_i$ ($1 \leq a_i \leq N$).
To determine the two head cows, FJ will hold his election in the following process:
- Choose an arbitrary subset $S$ of his cows that contains at least one cow but not all cows. FJ is able to choose cow $x$ as the first head cow if its votes appear most frequently among all votes cast by cows in $S$.
- FJ is able to choose cow $y$ as the second head cow if its votes appear most frequently among votes cast by cows not in $S$.
- For a fixed subset $S$, FJ denotes the diversity between his head cows as $|x - y|$. As FJ does not like having leaders with similar numbers, he wants to choose $S$ such that the diversity is maximized. Note that if FJ is not able to choose two distinct head cows, then the diversity is $0$.
However, some cows keep changing their minds, and FJ may have to rerun the election many times! Therefore, he asks you $Q$ ($1 \leq Q \leq 10^5$) queries. In each query, a cow changes their vote. After each query, he asks you for the maximum possible diversity among his new head cows.
INPUT FORMAT (input arrives from the terminal / stdin):
The first line contains $N$ and $Q$.The following line contains $a_1, a_2, \ldots, a_N$.
The following $Q$ lines contain two integers $i$ and $x$, representing the update $a_i = x$ ($1 \leq i, x \leq N$).
OUTPUT FORMAT (print output to the terminal / stdout):
Output $Q$ lines, the $i$'th of which is the maximum possible diversity after the first $i$ queries.SAMPLE INPUT:
5 3 1 2 3 4 5 3 4 1 2 5 2
SAMPLE OUTPUT:
4 3 2
After the first query, $a = [1, 2, 4, 4, 5]$. At the first step of the election, FJ can make $S = \{1, 3\}$. Here, cow $1$ receives one vote and cow $4$ receives one vote. Therefore, FJ can choose either cow $1$ or cow $4$ as its first head cow.
For all cows not in the election, cow $2$ receives one vote, cow $4$ receives one vote, and cow $5$ also receives one vote. Therefore, FJ can choose any one of cows $2$, $4$, or $5$ to be its second head cow.
To obtain the maximum diversity, FJ can choose cow $1$ as the first head cow and cow $5$ as the second head cow. Therefore, the diversity is $|1-5| = 4$.
After the second query, $a=[2,2,4,4,5]$ and FJ can make $S = \{4, 5\}$. Then, he can choose $5$ as the first head cow and cow $2$ as the second head cow. The maximum possible diversity is $|5 - 2| = 3$.
SAMPLE INPUT:
8 5 8 1 4 2 5 4 2 3 7 4 8 4 4 1 5 8 8 4
SAMPLE OUTPUT:
4 4 4 7 7
SCORING:
- Inputs 3-4: $N, Q \leq 100$
- Inputs 5-7: $N, Q \leq 3000$
- Inputs 8-15: No additional constraints.
Problem credits: Chongtian Ma and Haokai Ma
结果
Kimi K3.1 ProKimi
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 6.4k平均输出 token(含思考) ↓
- 23.1输出速度 tokens/s ↑
- 187 秒延迟 ↓
- 0.58×CPU 时间 / 官方解 ↓
- 同阶 2、更优 1时间复杂度(相对官方解)
DeepSeek Flash V4.1-1017DeepSeek
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 34.2k平均输出 token(含思考) ↓
- 197.4输出速度 tokens/s ↑
- 176 秒延迟 ↓
- 0.53×CPU 时间 / 官方解 ↓
- 同阶 3时间复杂度(相对官方解)
MiniMax M3.1 FlashMiniMax
2/3
解出的采样 ↑
- 100采样 1 · 解出
- 66.7采样 2 · 答案错误
- 100采样 3 · 解出
- 71.9k平均输出 token(含思考) ↓
- 169.2输出速度 tokens/s ↑
- 210 秒延迟 ↓
- 0.15×CPU 时间 / 官方解 ↓
- 更优 2时间复杂度(相对官方解)
↑ 越大越好,↓ 越小越好。得分 0–100,按官方时限判定,所有测试点都满分才算解出。CPU 时间 / 官方解为解出的答案在官方解最慢的 3 个测试点上的 CPU 时间之比(几何平均),只比较官方解至少需要 0.05 秒的题;复杂度按增长幂次相对官方解分类。判题与计分见 原理。
代码
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> a(N + 1), cnt(N + 1, 0); for (int i = 1; i <= N; ++i) { cin >> a[i]; ++cnt[a[i]]; } // buckets[k] contains all cow numbers having exactly k votes. vector<set<int>> buckets(N + 1); set<int> levels; // Nonempty positive vote counts, in increasing order. int maxVotes = 0; for (int i = 1; i <= N; ++i) { if (cnt[i] > 0) { if (buckets[cnt[i]].empty()) levels.insert(cnt[i]); buckets[cnt[i]].insert(i); maxVotes = max(maxVotes, cnt[i]); } } auto addToBucket = [&](int cow, int votes) { if (buckets[votes].empty()) levels.insert(votes); buckets[votes].insert(cow); }; auto removeFromBucket = [&](int cow, int votes) { buckets[votes].erase(cow); if (buckets[votes].empty()) levels.erase(votes); }; vector<int> values, mnPos, mxPos; values.reserve(700); mnPos.reserve(700); mxPos.reserve(700); auto computeAnswer = [&]() -> int { values.clear(); mnPos.clear(); mxPos.clear(); for (int k : levels) { values.push_back(k); mnPos.push_back(*buckets[k].begin()); mxPos.push_back(*buckets[k].rbegin()); } const int d = (int)values.size(); int p = d; int partnerMin = N + 1; int partnerMax = -1; int answer = 0; // A pair with vote counts v and w is possible exactly when v+w >= maxVotes. // For each v, maintain all positions whose counts are at least maxVotes-v. for (int i = 0; i < d; ++i) { int needed = maxVotes - values[i]; while (p > 0 && values[p - 1] >= needed) { --p; partnerMin = min(partnerMin, mnPos[p]); partnerMax = max(partnerMax, mxPos[p]); } answer = max(answer, partnerMax - mnPos[i]); answer = max(answer, mxPos[i] - partnerMin); } return answer; }; while (Q--) { int i, x; cin >> i >> x; int old = a[i]; a[i] = x; if (old != x) { int oldCount = cnt[old]; removeFromBucket(old, oldCount); --cnt[old]; if (cnt[old] > 0) addToBucket(old, cnt[old]); int targetOldCount = cnt[x]; if (targetOldCount > 0) removeFromBucket(x, targetOldCount); ++cnt[x]; addToBucket(x, cnt[x]); maxVotes = max(maxVotes, cnt[x]); while (maxVotes > 0 && buckets[maxVotes].empty()) --maxVotes; } cout << computeAnswer() << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> a(N + 1), cnt(N + 1, 0); for (int i = 1; i <= N; ++i) { cin >> a[i]; ++cnt[a[i]]; } map<int, set<int>> groups; for (int i = 1; i <= N; ++i) { if (cnt[i] > 0) groups[cnt[i]].insert(i); } auto removeCow = [&](int cow, int c) { auto it = groups.find(c); it->second.erase(cow); if (it->second.empty()) groups.erase(it); }; auto addCow = [&](int cow, int c) { groups[c].insert(cow); }; while (Q--) { int i, x; cin >> i >> x; int old = a[i]; if (old != x) { removeCow(old, cnt[old]); --cnt[old]; if (cnt[old] > 0) addCow(old, cnt[old]); if (cnt[x] > 0) removeCow(x, cnt[x]); ++cnt[x]; addCow(x, cnt[x]); a[i] = x; } int K = (int)groups.size(); vector<int> value(K), mn(K), mx(K); int p = 0; for (const auto &entry : groups) { value[p] = entry.first; mn[p] = *entry.second.begin(); mx[p] = *entry.second.rbegin(); ++p; } vector<int> sufMn(K), sufMx(K); for (int j = K - 1; j >= 0; --j) { sufMn[j] = mn[j]; sufMx[j] = mx[j]; if (j + 1 < K) { sufMn[j] = min(sufMn[j], sufMn[j + 1]); sufMx[j] = max(sufMx[j], sufMx[j + 1]); } } int M = value.back(); int answer = 0; for (int j = 0; j < K; ++j) { int need = M - value[j]; int k = lower_bound(value.begin(), value.end(), need) - value.begin(); if (k == K) continue; int low = sufMn[k], high = sufMx[k]; answer = max(answer, abs(mn[j] - low)); answer = max(answer, abs(mn[j] - high)); answer = max(answer, abs(mx[j] - low)); answer = max(answer, abs(mx[j] - high)); } cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; struct SegTree { int n, size; vector<int> tr; SegTree(int n_) : n(n_) { size = 1; while (size < n) size <<= 1; tr.assign(2 * size, 0); } void setValue(int pos, int value) { int p = pos + size - 1; tr[p] = value; for (p >>= 1; p; p >>= 1) tr[p] = max(tr[p << 1], tr[p << 1 | 1]); } int firstAtLeast(int value) const { if (tr[1] < value) return n + 1; int p = 1; while (p < size) { if (tr[p << 1] >= value) p <<= 1; else p = p << 1 | 1; } return p - size + 1; } int lastAtLeast(int value) const { if (tr[1] < value) return 0; int p = 1; while (p < size) { if (tr[p << 1 | 1] >= value) p = p << 1 | 1; else p <<= 1; } return p - size + 1; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> a(N + 1), cnt(N + 1, 0); map<int, set<int>> byCount; SegTree seg(N); for (int i = 1; i <= N; ++i) { cin >> a[i]; ++cnt[a[i]]; } for (int x = 1; x <= N; ++x) { if (cnt[x] > 0) { byCount[cnt[x]].insert(x); seg.setValue(x, cnt[x]); } } auto changeCount = [&](int x, int newCount) { int oldCount = cnt[x]; if (oldCount > 0) { auto &s = byCount[oldCount]; s.erase(x); if (s.empty()) byCount.erase(oldCount); } cnt[x] = newCount; if (newCount > 0) byCount[newCount].insert(x); seg.setValue(x, newCount); }; while (Q--) { int i, x; cin >> i >> x; int old = a[i]; if (old != x) { changeCount(old, cnt[old] - 1); changeCount(x, cnt[x] + 1); a[i] = x; } int M = byCount.rbegin()->first; int answer = 0; auto it = byCount.lower_bound((M + 1) / 2); for (; it != byCount.end(); ++it) { int c = it->first; int needed = max(1, M - c); int lo = seg.firstAtLeast(needed); int hi = seg.lastAtLeast(needed); for (int h : it->second) { answer = max(answer, abs(h - lo)); answer = max(answer, abs(h - hi)); } } cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> a(N + 1); vector<int> cnt(N + 1, 0); for (int i = 1; i <= N; i++) { cin >> a[i]; cnt[a[i]]++; } vector< set<int> > bucket(N + 1); set<int> activeFreqs; for (int v = 1; v <= N; v++) { if (cnt[v] > 0) { bucket[cnt[v]].insert(v); activeFreqs.insert(cnt[v]); } } vector<int> freqs; freqs.reserve(N + 1); vector<int> cumMin(N + 1), cumMax(N + 1); vector<int> exactMin(N + 1), exactMax(N + 1); auto computeAnswer = [&]() -> int { freqs.clear(); for (auto it = activeFreqs.rbegin(); it != activeFreqs.rend(); ++it) { freqs.push_back(*it); } int D = (int)freqs.size(); for (int i = 0; i < D; i++) { int f = freqs[i]; auto &s = bucket[f]; int mn = *s.begin(); int mx = *s.rbegin(); exactMin[i] = mn; exactMax[i] = mx; if (i == 0) { cumMin[i] = mn; cumMax[i] = mx; } else { cumMin[i] = min(cumMin[i - 1], mn); cumMax[i] = max(cumMax[i - 1], mx); } } int M = freqs[0]; int ans = 0; int r = D - 1; for (int i = 0; i < D; i++) { int f = freqs[i]; int need = M - f; while (r >= 0 && freqs[r] < need) { r--; } if (r < 0) continue; int minB = cumMin[r]; int maxB = cumMax[r]; int minA = exactMin[i]; int maxA = exactMax[i]; ans = max(ans, maxB - minA); ans = max(ans, maxA - minB); } return ans; }; for (int qi = 0; qi < Q; qi++) { int i, x; cin >> i >> x; int old = a[i]; if (old != x) { // Remove old vote. int oldCnt = cnt[old]; bucket[oldCnt].erase(old); if (bucket[oldCnt].empty()) { activeFreqs.erase(oldCnt); } cnt[old]--; if (cnt[old] > 0) { bucket[cnt[old]].insert(old); activeFreqs.insert(cnt[old]); } // Add new vote. int curCnt = cnt[x]; if (curCnt > 0) { bucket[curCnt].erase(x); if (bucket[curCnt].empty()) { activeFreqs.erase(curCnt); } } cnt[x]++; bucket[cnt[x]].insert(x); activeFreqs.insert(cnt[x]); a[i] = x; } cout << computeAnswer() << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> a(N + 1); vector<int> cnt(N + 1, 0); for (int i = 1; i <= N; i++) { cin >> a[i]; cnt[a[i]]++; } const int INF = 1e9; vector< set<int> > byFreq(N + 2); vector<int> mn(N + 2, INF), mx(N + 2, -INF); set<int> freqValues; for (int v = 1; v <= N; v++) { if (cnt[v] > 0) { byFreq[cnt[v]].insert(v); } } for (int k = 1; k <= N; k++) { if (!byFreq[k].empty()) { freqValues.insert(k); mn[k] = *byFreq[k].begin(); mx[k] = *byFreq[k].rbegin(); } } auto change = [&](int v, int delta) { int old = cnt[v]; int nw = old + delta; if (old > 0) { auto &s = byFreq[old]; s.erase(v); if (s.empty()) { freqValues.erase(old); mn[old] = INF; mx[old] = -INF; } else { mn[old] = *s.begin(); mx[old] = *s.rbegin(); } } cnt[v] = nw; if (nw > 0) { auto &s = byFreq[nw]; if (s.empty()) { freqValues.insert(nw); } s.insert(v); mn[nw] = *s.begin(); mx[nw] = *s.rbegin(); } }; static int freqs[1005]; static int pref[1005]; for (int qi = 0; qi < Q; qi++) { int pos, x; cin >> pos >> x; if (a[pos] != x) { int oldVote = a[pos]; change(oldVote, -1); change(x, +1); a[pos] = x; } int D = 0; for (auto it = freqValues.rbegin(); it != freqValues.rend(); ++it) { freqs[D++] = *it; } int M = freqs[0]; pref[0] = mn[freqs[0]]; for (int i = 1; i < D; i++) { pref[i] = min(pref[i - 1], mn[freqs[i]]); } int globalMin = pref[D - 1]; int p = D - 1; int ans = 0; for (int i = 0; i < D; i++) { int k = freqs[i]; int need = M - k; int leftmost; if (need <= 0) { leftmost = globalMin; } else { while (p >= 0 && freqs[p] < need) { p--; } if (p < 0) continue; leftmost = pref[p]; } ans = max(ans, mx[k] - leftmost); } cout << ans << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; int B = min(700, N); const int INF = 1e9; vector<int> a(N + 1); vector<int> freq(N + 1, 0); for (int i = 1; i <= N; i++) { cin >> a[i]; freq[a[i]]++; } vector< set<int> > byFreq(N + 1); set<int> activeFreqs; set<int> highIndices; int activeCnt = 0; for (int v = 1; v <= N; v++) { if (freq[v] > 0) { byFreq[freq[v]].insert(v); activeFreqs.insert(freq[v]); if (freq[v] > B) highIndices.insert(v); activeCnt++; } } vector<int> sufMin(B + 2), sufMax(B + 2); vector<int> exMin(B + 2), exMax(B + 2); vector<int> hf; vector<int> hMin, hMax; hf.reserve(N / max(1, B + 1) + 5); hMin.reserve(N / max(1, B + 1) + 5); hMax.reserve(N / max(1, B + 1) + 5); auto changeFreq = [&](int v, int delta) { int old = freq[v]; int nw = old + delta; if (old > 0) { byFreq[old].erase(v); if (byFreq[old].empty()) activeFreqs.erase(old); if (old > B) highIndices.erase(v); } if (old == 0 && nw > 0) activeCnt++; if (old > 0 && nw == 0) activeCnt--; freq[v] = nw; if (nw > 0) { if (byFreq[nw].empty()) activeFreqs.insert(nw); byFreq[nw].insert(v); if (nw > B) highIndices.insert(v); } }; string output; output.reserve(Q * 5); for (int qi = 0; qi < Q; qi++) { int i, x; cin >> i >> x; if (a[i] != x) { int old = a[i]; changeFreq(old, -1); changeFreq(x, +1); a[i] = x; } if (activeCnt < 2) { output += "0\n"; continue; } int M = *activeFreqs.rbegin(); int curMin = INF, curMax = -INF; if (!highIndices.empty()) { curMin = *highIndices.begin(); curMax = *highIndices.rbegin(); } for (int v = B; v >= 1; v--) { if (!byFreq[v].empty()) { int gmin = *byFreq[v].begin(); int gmax = *byFreq[v].rbegin(); exMin[v] = gmin; exMax[v] = gmax; curMin = min(curMin, gmin); curMax = max(curMax, gmax); } else { exMin[v] = INF; exMax[v] = -INF; } sufMin[v] = curMin; sufMax[v] = curMax; } int ans = 0; if (M <= B) { for (int af = 1; af <= M; af++) { if (exMin[af] == INF) continue; int need = M - af; if (need < 1) need = 1; int amin = exMin[af]; int amax = exMax[af]; int cmin = sufMin[need]; int cmax = sufMax[need]; if (amin != cmin) ans = max(ans, abs(amin - cmin)); if (amin != cmax) ans = max(ans, abs(amin - cmax)); if (amax != cmin) ans = max(ans, abs(amax - cmin)); if (amax != cmax) ans = max(ans, abs(amax - cmax)); } } else { hf.clear(); hMin.clear(); hMax.clear(); for (auto it = activeFreqs.lower_bound(B + 1); it != activeFreqs.end(); ++it) { int f = *it; int gmin = *byFreq[f].begin(); int gmax = *byFreq[f].rbegin(); hf.push_back(f); hMin.push_back(gmin); hMax.push_back(gmax); } int curMinH = INF, curMaxH = -INF; for (int idx = (int)hf.size() - 1; idx >= 0; idx--) { curMinH = min(curMinH, hMin[idx]); curMaxH = max(curMaxH, hMax[idx]); hMin[idx] = curMinH; hMax[idx] = curMaxH; } int half = (M + 1) / 2; for (auto it = activeFreqs.lower_bound(half); it != activeFreqs.end(); ++it) { int f = *it; for (int cowVal : byFreq[f]) { int need = M - f; if (need < 1) need = 1; int cmin, cmax; if (need <= B) { cmin = sufMin[need]; cmax = sufMax[need]; } else { int idx = lower_bound(hf.begin(), hf.end(), need) - hf.begin(); if (idx == (int)hf.size()) continue; cmin = hMin[idx]; cmax = hMax[idx]; } if (cmin != cowVal) ans = max(ans, abs(cowVal - cmin)); if (cmax != cowVal) ans = max(ans, abs(cowVal - cmax)); } } } output += to_string(ans); output += '\n'; } cout << output; return 0; }
#include <bits/stdc++.h> using namespace std; class VoteTracker { static constexpr int INF = 1'000'000'000; int n; int maxFrequency = 0; vector<int> frequency; vector<set<int>> bucket; // exactMin[f], exactMax[f]: extreme labels having exactly f votes. vector<int> exactMin, exactMax; // suffixMin[f], suffixMax[f]: extreme labels having at least f votes. vector<int> suffixMin, suffixMax; // Nonempty frequency buckets. vector<int> activeFrequencies; vector<int> activePosition; void insertIntoBucket(int label, int f) { auto &s = bucket[f]; if (s.empty()) { activePosition[f] = (int)activeFrequencies.size(); activeFrequencies.push_back(f); } s.insert(label); exactMin[f] = min(exactMin[f], label); exactMax[f] = max(exactMax[f], label); } void eraseFromBucket(int label, int f) { auto &s = bucket[f]; auto it = s.find(label); s.erase(it); if (s.empty()) { exactMin[f] = INF; exactMax[f] = -INF; int pos = activePosition[f]; int last = activeFrequencies.back(); activeFrequencies[pos] = last; activePosition[last] = pos; activeFrequencies.pop_back(); activePosition[f] = -1; } else { exactMin[f] = *s.begin(); exactMax[f] = *s.rbegin(); } } void refreshSuffix(int f) { suffixMin[f] = min(exactMin[f], suffixMin[f + 1]); suffixMax[f] = max(exactMax[f], suffixMax[f + 1]); } void normalizeMaximum() { while (maxFrequency > 0 && bucket[maxFrequency].empty()) { --maxFrequency; } } public: explicit VoteTracker(vector<int> initial) : n((int)initial.size() - 1), frequency(std::move(initial)), bucket(n + 1), exactMin(n + 1, INF), exactMax(n + 1, -INF), suffixMin(n + 2, INF), suffixMax(n + 2, -INF), activePosition(n + 1, -1) { for (int label = 1; label <= n; ++label) { if (frequency[label] > 0) { auto &s = bucket[frequency[label]]; s.insert(s.end(), label); } } for (int f = 1; f <= n; ++f) { if (!bucket[f].empty()) { exactMin[f] = *bucket[f].begin(); exactMax[f] = *bucket[f].rbegin(); activePosition[f] = (int)activeFrequencies.size(); activeFrequencies.push_back(f); } } maxFrequency = activeFrequencies.empty() ? 0 : activeFrequencies.back(); for (int f = n; f >= 1; --f) { refreshSuffix(f); } } void removeOneVote(int label) { int oldFrequency = frequency[label]; eraseFromBucket(label, oldFrequency); frequency[label] = oldFrequency - 1; if (oldFrequency > 1) { insertIntoBucket(label, oldFrequency - 1); } // This label leaves exactly the set of labels with frequency >= oldFrequency. refreshSuffix(oldFrequency); normalizeMaximum(); } void addOneVote(int label) { int oldFrequency = frequency[label]; if (oldFrequency > 0) { eraseFromBucket(label, oldFrequency); } frequency[label] = oldFrequency + 1; insertIntoBucket(label, oldFrequency + 1); // This label enters exactly the set of labels with frequency >= oldFrequency+1. refreshSuffix(oldFrequency + 1); maxFrequency = max(maxFrequency, oldFrequency + 1); normalizeMaximum(); } int bestDiversity() const { int answer = 0; for (int f : activeFrequencies) { // A partner with frequency g must satisfy f+g >= maxFrequency. int required = max(1, maxFrequency - f); answer = max(answer, suffixMax[required] - exactMin[f]); answer = max(answer, exactMax[f] - suffixMin[required]); } return answer; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> a(N + 1); vector<int> count(N + 1, 0); for (int i = 1; i <= N; ++i) { cin >> a[i]; ++count[a[i]]; } VoteTracker tracker(std::move(count)); while (Q--) { int i, x; cin >> i >> x; if (a[i] != x) { tracker.removeOneVote(a[i]); tracker.addOneVote(x); a[i] = x; } cout << tracker.bestDiversity() << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; class ElectionSolver { struct CacheCell { int nonEdge = -1; int oneEdge = -1; uint32_t nonGen1 = 0, nonGen2 = 0; uint32_t oneGen1 = 0, oneGen2 = 0; }; int N; vector<int> a, cnt; // group[c] contains the cows receiving exactly c votes. vector<set<int>> group; set<int> activeCounts; // Slots give active vote-count values compact cache indices. vector<int> slotOf; vector<int> slotValue; vector<uint32_t> slotGeneration; vector<int> freeSlots; vector<vector<CacheCell>> cacheCells; int currentAnswer = 0; static vector<int> firstK(const set<int>& s, int k) { vector<int> result; result.reserve(k); for (auto it = s.begin(); it != s.end() && (int)result.size() < k; ++it) { result.push_back(*it); } return result; } static vector<int> lastKDescending(const set<int>& s, int k) { vector<int> result; result.reserve(k); auto it = s.end(); while (it != s.begin() && (int)result.size() < k) { --it; result.push_back(*it); } return result; } static vector<int> extremeIds(const set<int>& s) { vector<int> result = firstK(s, 3); vector<int> last = lastKDescending(s, 3); result.insert(result.end(), last.begin(), last.end()); sort(result.begin(), result.end()); result.erase(unique(result.begin(), result.end()), result.end()); return result; } int allocateSlot(int countValue) { int s; if (!freeSlots.empty()) { s = freeSlots.back(); freeSlots.pop_back(); slotValue[s] = countValue; ++slotGeneration[s]; } else { s = (int)slotValue.size(); slotValue.push_back(countValue); slotGeneration.push_back(1); cacheCells.emplace_back(); for (auto& row : cacheCells) { row.resize(s + 1); } } slotOf[countValue] = s; return s; } void markDirty(int c1, int c2) { if (c1 <= 0 || c2 <= 0) return; int s1 = slotOf[c1], s2 = slotOf[c2]; if (s1 < 0 || s2 < 0) return; if (s1 > s2) swap(s1, s2); cacheCells[s1][s2].nonEdge = -1; cacheCells[s1][s2].oneEdge = -1; } void moveBetweenGroups(int cow, int oldCount, int newCount) { if (oldCount == newCount) return; if (oldCount > 0) { group[oldCount].erase(cow); int s = slotOf[oldCount]; if (s >= 0) ++slotGeneration[s]; if (group[oldCount].empty()) { if (s >= 0) { slotOf[oldCount] = -1; freeSlots.push_back(s); } activeCounts.erase(oldCount); } } if (newCount > 0) { int s = slotOf[newCount]; if (s < 0) s = allocateSlot(newCount); ++slotGeneration[s]; group[newCount].insert(cow); activeCounts.insert(newCount); } } bool adjacent(int x, int y) const { return a[x] == y || a[y] == x; } // For two cows whose counts sum to M, they can be leaders exactly // when neither votes for the other. int computeNonEdgeBest(int c, int d) { const auto& C = group[c]; const auto& D = group[d]; int best = 0; int minC = *C.begin(); int minD = *D.begin(); int limX = (int)min<long long>((long long)d + 2, C.size()); int limY = (int)min<long long>((long long)c + 2, D.size()); vector<int> firstX = firstK(C, limX); vector<int> lastX = lastKDescending(C, limX); vector<int> firstY = firstK(D, limY); vector<int> lastY = lastKDescending(D, limY); // Cases with the cow from D having the larger index. for (int y : lastY) { if (y - minC <= best) break; for (int x : firstX) { if (x >= y) break; if (!adjacent(x, y)) { best = max(best, y - x); break; } } } // Cases with the cow from C having the larger index. for (int x : lastX) { if (x - minD <= best) break; for (int y : firstY) { if (y >= x) break; if (!adjacent(x, y)) { best = max(best, x - y); break; } } } return best; } // For two cows whose counts sum to M+1, at most one directed // relation between them is allowed. bool validOneEdge(int x, int y, int c, int d) const { int u = (a[y] == x); int v = (a[x] == y); int p = c - u; int q = d - v; return p >= 1 && q >= 1 && u + v <= 1; } int computeOneEdgeBest(int c, int d) { vector<int> C = extremeIds(group[c]); vector<int> D = extremeIds(group[d]); int best = 0; for (int x : C) { for (int y : D) { if (x == y) continue; if (validOneEdge(x, y, c, d)) { best = max(best, abs(x - y)); } } } return best; } int getNonEdgeBest(int c, int d) { int s1 = slotOf[c], s2 = slotOf[d]; int lo = min(s1, s2), hi = max(s1, s2); CacheCell& cell = cacheCells[lo][hi]; if (cell.nonEdge < 0 || cell.nonGen1 != slotGeneration[lo] || cell.nonGen2 != slotGeneration[hi]) { cell.nonEdge = computeNonEdgeBest(c, d); cell.nonGen1 = slotGeneration[lo]; cell.nonGen2 = slotGeneration[hi]; } return cell.nonEdge; } int getOneEdgeBest(int c, int d) { int s1 = slotOf[c], s2 = slotOf[d]; int lo = min(s1, s2), hi = max(s1, s2); CacheCell& cell = cacheCells[lo][hi]; if (cell.oneEdge < 0 || cell.oneGen1 != slotGeneration[lo] || cell.oneGen2 != slotGeneration[hi]) { cell.oneEdge = computeOneEdgeBest(c, d); cell.oneGen1 = slotGeneration[lo]; cell.oneGen2 = slotGeneration[hi]; } return cell.oneEdge; } int calculateAnswer() { int M = *activeCounts.rbegin(); vector<int> values(activeCounts.begin(), activeCounts.end()); int K = (int)values.size(); vector<int> suffixMin(K), suffixMax(K); for (int i = K - 1; i >= 0; --i) { int c = values[i]; int mn = *group[c].begin(); int mx = *group[c].rbegin(); if (i + 1 < K) { mn = min(mn, suffixMin[i + 1]); mx = max(mx, suffixMax[i + 1]); } suffixMin[i] = mn; suffixMax[i] = mx; } int answer = 0; // If the two vote counts sum to at least M+2, the pair is // always feasible, regardless of the directed votes between them. int firstValid = K; for (int i = 0; i < K; ++i) { int c = values[i]; int threshold = M - c + 2; while (firstValid > 0 && values[firstValid - 1] >= threshold) { --firstValid; } if (firstValid == K) continue; int mn = *group[c].begin(); int mx = *group[c].rbegin(); answer = max(answer, mx - suffixMin[firstValid]); answer = max(answer, suffixMax[firstValid] - mn); } // Counts summing to M+1. for (int c : values) { int d = M + 1 - c; if (c > d || d <= 0 || group[d].empty()) continue; answer = max(answer, getOneEdgeBest(c, d)); } // Counts summing to M. for (int c : values) { int d = M - c; if (c > d || d <= 0 || group[d].empty()) continue; answer = max(answer, getNonEdgeBest(c, d)); } return answer; } public: ElectionSolver(int n, vector<int> initialVotes) : N(n), a(std::move(initialVotes)), cnt(n + 1, 0), group(n + 1), slotOf(n + 1, -1) { for (int v : a) ++cnt[v]; for (int cow = 1; cow <= N; ++cow) { if (cnt[cow] > 0) { group[cnt[cow]].insert(group[cnt[cow]].end(), cow); activeCounts.insert(cnt[cow]); } } for (int c : activeCounts) allocateSlot(c); currentAnswer = calculateAnswer(); } int update(int cow, int newVote) { int oldVote = a[cow]; if (oldVote == newVote) return currentAnswer; a[cow] = newVote; int oldCount = cnt[oldVote]; --cnt[oldVote]; moveBetweenGroups(oldVote, oldCount, oldCount - 1); int newCount = cnt[newVote]; ++cnt[newVote]; moveBetweenGroups(newVote, newCount, newCount + 1); // Only relations involving this cow's outgoing vote changed. markDirty(cnt[cow], cnt[oldVote]); markDirty(cnt[cow], cnt[newVote]); currentAnswer = calculateAnswer(); return currentAnswer; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> a(N + 1); for (int i = 1; i <= N; ++i) cin >> a[i]; ElectionSolver solver(N, std::move(a)); while (Q--) { int i, x; cin >> i >> x; cout << solver.update(i, x) << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; class MaxSegTree { int n, base; vector<int> tree; public: MaxSegTree(int n_, const vector<int>& values) : n(n_), base(1) { while (base < n) base <<= 1; tree.assign(2 * base, 0); for (int i = 1; i <= n; ++i) { tree[base + i - 1] = values[i]; } for (int p = base - 1; p >= 1; --p) { tree[p] = max(tree[2 * p], tree[2 * p + 1]); } } void update(int pos, int value) { int p = base + pos - 1; tree[p] = value; for (p >>= 1; p >= 1; p >>= 1) { tree[p] = max(tree[2 * p], tree[2 * p + 1]); } } // Maximum over count values in [pos, n]. int suffixMax(int pos) const { int l = base + pos - 1; int r = base + n; int result = 0; while (l < r) { if (l & 1) result = max(result, tree[l++]); if (r & 1) result = max(result, tree[--r]); l >>= 1; r >>= 1; } return result; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> a(N + 1); vector<int> cnt(N + 1, 0); for (int i = 1; i <= N; ++i) { cin >> a[i]; ++cnt[a[i]]; } // bucket[c] contains all cows receiving exactly c votes. vector<set<int>> bucket(N + 1); for (int cow = 1; cow <= N; ++cow) { if (cnt[cow] > 0) { auto& s = bucket[cnt[cow]]; s.insert(s.end(), cow); } } vector<int> exactMin(N + 1, 0); vector<int> exactMax(N + 1, 0); // The occurring positive vote counts. vector<int> activeCounts; vector<int> activePos(N + 1, -1); activeCounts.reserve(700); auto activate = [&](int c) { if (activePos[c] == -1) { activePos[c] = (int)activeCounts.size(); activeCounts.push_back(c); } }; auto deactivate = [&](int c) { int p = activePos[c]; int last = activeCounts.back(); activeCounts[p] = last; activePos[last] = p; activeCounts.pop_back(); activePos[c] = -1; }; for (int c = 1; c <= N; ++c) { if (!bucket[c].empty()) { activate(c); exactMin[c] = *bucket[c].begin(); exactMax[c] = *bucket[c].rbegin(); } } auto removeFromBucket = [&](int c, int cow) { auto& s = bucket[c]; s.erase(cow); if (s.empty()) { deactivate(c); exactMin[c] = 0; exactMax[c] = 0; } else { exactMin[c] = *s.begin(); exactMax[c] = *s.rbegin(); } }; auto addToBucket = [&](int c, int cow) { auto& s = bucket[c]; if (s.empty()) activate(c); s.insert(cow); exactMin[c] = *s.begin(); exactMax[c] = *s.rbegin(); }; // The segment tree stores the largest cow number having each exact count. MaxSegTree seg(N, exactMax); // R[t] = largest cow number receiving at least t votes. vector<int> R(N + 2, 0); for (int t = N; t >= 1; --t) { R[t] = max(exactMax[t], R[t + 1]); } int M = 0; for (int c : activeCounts) M = max(M, c); auto computeAnswer = [&]() { int answer = 0; for (int c : activeCounts) { int needed = M - c; if (needed < 1) needed = 1; answer = max(answer, R[needed] - exactMin[c]); } return answer; }; int answer = computeAnswer(); while (Q--) { int voter, newTarget; cin >> voter >> newTarget; int oldTarget = a[voter]; if (oldTarget != newTarget) { int oldCount = cnt[oldTarget]; int newCount = cnt[newTarget]; // The old target's vote count changes: oldCount -> oldCount - 1. removeFromBucket(oldCount, oldTarget); if (oldCount > 1) { addToBucket(oldCount - 1, oldTarget); } // The new target's vote count changes: newCount -> newCount + 1. if (newCount > 0) { removeFromBucket(newCount, newTarget); } addToBucket(newCount + 1, newTarget); cnt[oldTarget] = oldCount - 1; cnt[newTarget] = newCount + 1; a[voter] = newTarget; // Update all exact-count buckets that could have changed. vector<int> changed; changed.push_back(oldCount); changed.push_back(oldCount - 1); changed.push_back(newCount); changed.push_back(newCount + 1); sort(changed.begin(), changed.end()); changed.erase(unique(changed.begin(), changed.end()), changed.end()); for (int c : changed) { if (c >= 1 && c <= N) { seg.update(c, exactMax[c]); } } M = max(M, newCount + 1); while (M > 0 && exactMax[M] == 0) { --M; } // Threshold membership changes only at these two thresholds. R[oldCount] = seg.suffixMax(oldCount); if (newCount + 1 != oldCount) { R[newCount + 1] = seg.suffixMax(newCount + 1); } answer = computeAnswer(); } cout << answer << '\n'; } return 0; }