a578中等因數倍數篩與前綴最佳值
CPE:Divisor Game (UVa 11960)
一次預算支援五萬次含平手規則的查詢。
解題思路
要算1..U的因數個數,逐一枚舉d,再把d的每個倍數的計數加1。每個正因數都會且只會為它的倍數貢獻一次,所以得到所有divisors[x],總迭代量是U(1+1/2+…+1/U),即O(U log U)。
接著由1往U掃描,best保存目前因數數量最多且值最大的整數。遇到divisors[x]≥divisors[best]就更新成x,等號恰好實現平手取較大者。保存prefix[x]=best,每個查詢直接索引。讀完全部查詢後只預算到最大N即可;Python以array壓縮計數與答案記憶體。
Step-by-step animation
示意:查詢N=10
步驟 1 / 3
走到6
6的因數1、2、3、6,共4個,成為最佳。
d(6)=4
- best
- 6
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
vector<int> q(t);
for (int &x : q)
cin >> x;
int limit = q.empty() ? 0 : *max_element(q.begin(), q.end());
vector<int> divisors(limit + 1), prefix(limit + 1);
for (int d = 1; d <= limit; ++d)
for (int v = d; v <= limit; v += d)
++divisors[v];
int best = 0;
for (int v = 1; v <= limit; ++v) {
if (divisors[v] >= divisors[best])
best = v;
prefix[v] = best;
}
for (int v : q)
cout << prefix[v] << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。