版本比较
N Factor 做题记录
正文
增加 552 行删除 59 行
4 行未改动567899101112131314151516171718192019202324212223246 行未改动31323334393536413738394041424344454647484950515253545556575859606162636465666768697071724973747576537778798057818259838461858663648788896890919293729495969776989910010110210310410510610784108109868711011111211311493941151161179611811998991001011021201211221231241051251261271281091291301311321331341151351361171371381191391401211411421231431441251451461271471481291491501311511521531541551561571581591331341351361371381391401411421431441601611621631461641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456461591601611626476486496506516526536546556566576584 行未改动> 其实是上次 AHC 打得很烂,表现分才青。
题意很简单:构造 $1000$ 个 $10^9$ 以内的正整数,让它们的因数集合的大小尽可能大。
本人较菜,目前 $\text{Rank 3}$。本人较菜,目前 $\text{Rank 2}$。
大部分代码均由 `GTP-5 Free / Grok 4 Fast` 赞助,所以不放了。
---广告:
**声明**:我们想自己办一个类 AHC 的启发式比赛,欢迎参与讨论。
因为这是启发式竞赛,都是各个参赛者用心参与的,因此个人认为互相分享,找到最更优解都是可以的。快来参加第二届 `N Factors`:<https://www.luogu.com.cn/contest/285919>!
和各个大佬讨论交流也能增长见识(尤其是骗分相关),也能学到一些小技巧,所以我就分享出来了。
**侵删**。
~~为以后挖矿做准备。~~
## Prepare
一些链接:
6 行未改动- [多线程](https://zhuanlan.zhihu.com/p/613630658),但我用的是人工多线程。
## Part 1
#### naive下面这部分是我 $3$ 分钟写完凑数的。
脑抽了,打了一个随机选质数跑高合成数,只有 $9$ 万分。#### Naive
输出 $1\sim1000$,简单 $1000$ 分,不知道这个分数的人想干什么。
:::info[猜你不想要]```pythonfor i in range(1,1001): print(i,end=' ')```:::
#### Common
脑抽了,打了一个随机选质数跑高合成数,只有 $9$ 万分,甚至不如乱搞。
太丢人了,代码不放了。
#### Plus
所以用现成的高合成数。
观察发现 $10^6$ 以内的最大高合成数是 $720720$,输出祂的倍数。
:::info[$119300$ 分]```pythoncnt=0for i in range(10**9//720720*720720,0,-720720): print(i,end=' ') cnt+=1 if cnt==1000:break```:::
## Part 2
感谢 [YYZ1208](https://www.luogu.com.cn/user/875283) 提供的思路。
#### naive#### Naive
考虑朴素构造,挑选若干个高合成数,把他们扔上去,没试过。
#### common#### Common
挑选一个合适的基,有尽量多的因数(高合成数),然后输出它的 $1,2,3,\dots,1000$ 倍。
估计 $9$ 万分。估计 $9$ 万分,是的,不如乱搞。
#### plus#### Plus
改为输出它的质数倍。改为输出它的质数倍,避免重复,有 $13$ 万分。
如果你挑的不好的话(如我)有 $13$ 万分。
具体的:
- 第 $1000$ 个质数是 $7919$,可以在数字帝国查看 <https://zh.numberempire.com/1000#:~:text=1009-,1000th%20%E8%B4%A8%E6%95%B0,-7919>。- 你可以选择小于 $\lfloor\frac{10^9}{7919}\rfloor=126278$ 的高合成数,在 OEIS 上看,是 $110880$,所以输出它的质数倍。- 你可以选择小于等于 $\lfloor\frac{10^9}{7919}\rfloor=126278$ 的高合成数,在 OEIS 上看,是 $110880$,所以输出它的质数倍。
理论得分:$d(110880)\times1000=134\times1000=13.4\times10^4$。
#### extra#### Extra
发现选质数倍很蠢,因为你选一个 $6$ 就等效选了 $2,3$,因此可以改乘小高合成数。
实现的好一点,可以获得 YYZ1208 的 $22$ 万分。实现的精细一点,可以获得 YYZ1208 的 $22$ 万分。
代码别找我,找 YYZ1208 吧。
## Part 3
不知道是谁跟我说直接跑贪心,每次选一个使当前分数最大的选就有 $22.5$ 万多分,所以这样很有前途。
考虑随机化乱搞。
感谢 [cheng2010](https://www.luogu.com.cn/user/1045879) 的伟大思路。#### Naive
#### naive
直接强上,没试过。
具体来说,就是随机修改 $1000$ 个数中的某一个,然后计算贡献。
- 如果你打的是模拟退火: * 如果更劣,以一定概率接受; * 否则直接接受。 - 如果更劣,以一定概率接受; - 否则直接接受。- 如果你打的是爬山算法: * 只有更优才接受。 - 只有更优才接受。
我是后者,cheng2010 是前者。
因此补充对爬山的小优化:
1. 如果连续很多次没有更优,说明陷入局部解,随机修改若干个重跑。:::info[爬山的小优化]1. 如果连续很多次没有更优,说明陷入局部最优解,随机修改若干个重跑;2. 可以每隔固定迭代次数记录到文件,下次开跑时直接读文件。:::
#### common#### Common
观察刚刚获得的输出,发现,所有数都是 $10$ 的倍数,大胆猜测,每个数都是 $10$ 的倍数的情况最优,问题缩减到原来的 $\frac{1}{10}$,跑起来嘎嘎快。
#### plus#### Plus
观察发现,一个数小于 $\frac{10^9}{2}$ 可以乘上 $2$,更不劣。
同时观察发现,每个数都是 $60$ 的倍数的情况最优,所以跑的更快了。
---同时直接大胆猜测(其实还是观察发现),选中的数最大质因子不会很大,所以扔掉所有质因子大于第 $500$ 个质数的数。
##### Interrupt我们期望每个数的因数尽可能多,可以提前打一个筛,把所有不符合的数筛掉,一共发现只有 $\approx2\times10^5$ 个,所以更容易跑出更优解。
有两种质因数分解方法,一种是质数筛到 $\sqrt{10^9}\approx40000$,然后暴力除即可,另一种是 Pollard-Rho 算法,太懒了没打。#### Extra
同时还有一种思路,预处理 $1\sim10^9$ 内每个数的最小质因子,这样就可以 $O(d)$ 时间复杂度类获得了,但是没有实际用途。可以利用刚刚筛出来的数的性质,跑出来前 $500$ 个质数,试除法就能光速因式分解。
---不妨借鉴预处理的思路,直接把 $\approx2\times10^5$ 个数的因数都晒出来,需要时直接调用就行了。
#### extra实测快了不止一点,同时可以手打哈希表,可以从 [Library Checker](https://judge.yosupo.jp/problem/associative_array) 上拷一个最快的。
OK,继续,考虑在常数方面优化(因为跑得更快更容易在相同时间跑出更优解)。#### Code
为了提高效率,你可以卡常。给出主函数:
具体的::::info[爬山]```cppint main(){ ios::sync_with_stdio(false); cin.tie(nullptr); sieve(); prepare();
1. 质数筛,这个好像没卵用;2. 手写哈希表,提高缓存命中率;3. 开 `#pragma GCC optimize("O3", "Ofast", "unroll-loops", "inline")`;4. 考虑只选择因数个数大于 $360$ 的数;5. 上述的数只有 $\approx2\times10^5$ 个,每个数都预处理因数,放在一个文件里,随机数就从里面选;6. 观察到一个有较大质数作为因数的数不优,替换为高合成数可能更优(存疑);7. 同时可以发现最大质数较小,分解也更快;8. 考虑如下扰动:修改最小的 $5$ 个数,同时修改随机的 $5$ 个数;9. 考虑一次修改多个数,如修改 $5$ 个数,每个数 $5$ 个候选值,$5^5$ 次枚举;10. 考虑用多进制格雷码优化;11. 哈希表定期重构,消除墓碑;12. 租一台轻量级服务器,闲置时还能真的挖矿(国内个人挖矿应该合规,之前在哪看到的)。 ID = time(nullptr) % 10000; cerr << "ID: " << ID << "\nWide:\n"; system(("title ID: " + to_string(ID)).c_str());
最近考虑找同学借服务器,等我好消息。 State cur; cur.a.resize(N); cur.adiv.resize(N); ifstream fin(filename); bool loaded = false; if (fin) { for (int i = 0; i < N; i++) if (!(fin >> cur.a[i])) { loaded = false; break; } if (!fin.fail()) loaded = true; fin.close(); } if (!loaded) for (int i = 0; i < N; i++) cur.a[i] = random_value();
// fill cur.adiv using precomputed divisors when available vector<pair<int, int>> ftmp; for (int i = 0; i < N; i++) { auto it = value_to_idx.find(cur.a[i]); if (it != value_to_idx.end()) cur.adiv[i] = predivs[it->second]; else { factorize(cur.a[i], ftmp); get_divisors(ftmp, cur.adiv[i]); } cur.adiv[i].shrink_to_fit(); }
cur.cnt.clear(); cur.score = 0; for (int i = 0; i < N; i++) for (int d : cur.adiv[i]) { int before = cur.cnt.get(d); cur.cnt.inc(d); if (before == 0) cur.score++; }
State best = cur; cerr << "init score=" << best.score << "\n";
const int CAND = 4; const ll LOG_INTERVAL = 1000000; const ll REBUILD_INTERVAL = 1000000000; const ll RESTART_NO_IMPROVE = 40000000; ll iter = 0; ll last_improve_iter = 0;
vector<vector<int>> cand_divs(CAND); while (true) { iter++; int idx = rndint(0, N - 1); const vector<int> &divs_old = cur.adiv[idx]; int oldv = cur.a[idx];
int best_cand = oldv; ll best_cand_score = cur.score - 1; int cand_count = 0; for (int t = 0; t < CAND; t++) { int v = random_value(); if (v == oldv) continue; // use precomputed divisors when available auto it = value_to_idx.find(v); if (it != value_to_idx.end()) { cand_divs[cand_count] = predivs[it->second]; } else { factorize(v, ftmp); get_divisors(ftmp, cand_divs[cand_count]); } cand_count++; ll delta = compute_delta(cur, divs_old, cand_divs[cand_count - 1]); ll trial_score = cur.score + delta; if (trial_score > best_cand_score) { best_cand_score = trial_score; best_cand = v; } }
if (cur.cnt.need_rebuild()) { cur.cnt.rebuild(); cerr << "[counter rebuild] unique=" << cur.cnt.unique_cnt << " tombs=" << cur.cnt.tomb_cnt << "\n"; }
if (best_cand_score >= cur.score && best_cand != oldv) { int oldscore = cur.score; del(cur, divs_old); vector<int> new_divs; auto itb = value_to_idx.find(best_cand); if (itb != value_to_idx.end()) new_divs = predivs[itb->second]; else { factorize(best_cand, ftmp); get_divisors(ftmp, new_divs); } cur.adiv[idx] = new_divs; cur.a[idx] = best_cand; add(cur, new_divs);
if (cur.score > best.score) { best = cur; last_improve_iter = iter; ofstream fout(filename); for (int i = 0; i < N; i++) fout << best.a[i] << " "; fout << "\n"; fout.close(); cerr << "NEW BEST iter=" << iter << " score=" << best.score << "\n"; record(best); } else if (cur.score != oldscore) { last_improve_iter = iter; } }
if (iter % LOG_INTERVAL == 0) { // logging(cur); cerr << "\titer=" << iter << " cur.score=" << cur.score << " last_imp=" << (iter - last_improve_iter) << " Time clock()=" << clock() << "\n"; }
if (iter % REBUILD_INTERVAL == 0) { cerr << "[rebuild] iter=" << iter << "\n"; rebuild(cur, best); }
if (iter - last_improve_iter > RESTART_NO_IMPROVE && iter - last_improve_iter < RESTART_NO_IMPROVE + 2) { cerr << "[restart] iter=" << iter << " no improve for " << (iter - last_improve_iter) << "\n"; sort(cur.a.begin(), cur.a.end()); for (int i = 0; i < 10; i++) { cur.a[i] = random_value(); cur.a[rng() % N] = random_value(); } for (int i = 0; i < N; i++) { auto it = value_to_idx.find(cur.a[i]); if (it != value_to_idx.end()) cur.adiv[i] = predivs[it->second]; else { factorize(cur.a[i], ftmp); get_divisors(ftmp, cur.adiv[i]); } cur.adiv[i].shrink_to_fit(); }
cur.cnt.clear(); cur.score = 0; for (int i = 0; i < N; i++) for (int d : cur.adiv[i]) { int before = cur.cnt.get(d); cur.cnt.inc(d); if (before == 0) cur.score++; } } } return 0;}
```:::
## Part 4
观察发现 [cheng2010](https://www.luogu.com.cn/user/1045879) 的模拟退火跑得分数很高,因为模拟退火不容易卡局部最优解。
#### Common
直接敲诈祂,搞到了祂的代码和数据。
祂的数据是啥啊,随便爬山挖一挖就多了 $30$ 分。
祂的模拟退火是啥啊,打的这么垃圾。
考虑自己打一个,参数已经有人调好了,对着爬山改就行了。
#### Plus
由于爬山是每次改一个数,真的很难跳出局部最优解,观察某人的实现,祂是每次改修改 $8$ 个数,每次以极小概率接受更劣解。
至于祂的温度是怎么打的,没看懂,照搬即可。
#### Extra
模拟退火单独一个跑起来还是太费劲了,所以我们考虑细节上优化实现。
具体来说,我们希望多线程一起跑,最大效率利用 CPU 资源挖~~矿~~解。
所以我们可以这样实现,启动后从 `best.txt` 里读取最优解,然后开跑。
如果跑出更优解,就选择记录下来,存到 `best.txt`,但这是就会有一个问题,如果一个程序从 $100$ 分先跑出了 $102$ 分,然后另一个跑出了 $101$ 分,这样 `best.txt` 就会被更差的覆盖了。
所以你可以打一个多线程来控制,防止误写,或者写的时候判断一下。
但是我选择另一种方法,直接写进对应分数的文件里,即跑出 $102$ 分时写进 `102.txt`,跑出 $101$ 分时写进 `101.txt`,这样即使 `best` 被覆写,也可以保留不同的分数。
这样做还有一个优点,可以获得不同局部的最优解,丰富样本的多样性。
当然可以拼上爬山的小优化,如果跑了很多遍都没有更优解,就直接读取 `best.txt` 重启(记得重启温度,但是我不知道某人的温度是怎么定的,所以没打)。
#### Code
同样只给出主函数,可以同时运行多个。
:::info[多开参照]本机是 `Intel(R) Core(TM) i5-10500 CPU @ 3.10GHz`,$6$ 核 $12$ 线程,以下是实测表。
第一列表示开了几个,`iters` 表示迭代次数,每次测试皆跑 $2\times10^6$ 次迭代,取平均值。
```1: 1*2000000 iters used 169.251s=84.625500s/M2: 2*2000000 iters used 177.247s=44.311750s/M3: 3*2000000 iters used 218.626s=36.437667s/M4: 4*2000000 iters used 268.863s=33.607875s/M5: 5*2000000 iters used 358.254s=35.825400s/M6: 6*2000000 iters used 512.126s=42.677167s/M```:::
:::info[模拟退火]```cppint main(int argc, char **argv){ ios::sync_with_stdio(false); cin.tie(nullptr);
sieve(); prepare();
double hours_per_run = 300.0; if (argc >= 2) hours_per_run = atof(argv[1]); if (argc >= 3) { uint64_t s = (uint64_t)stoull(string(argv[2])); rng.seed(s); }
int ID = (int)(time(nullptr) % 10000); cerr << "ID: " << ID << "\nSA\n"; system(("title ID: " + to_string(ID)).c_str());
State cur; cur.a.resize(N); cur.adiv.resize(N);
if (!try_load_best(cur)) { for (int i = 0; i < N; ++i) cur.a[i] = random_value(); vector<pair<int, int>> ftmp; for (int i = 0; i < N; ++i) { auto it = value_to_idx.find(cur.a[i]); if (it != value_to_idx.end()) cur.adiv[i] = predivs[it->second]; else { factorize(cur.a[i], ftmp); get_divisors(ftmp, cur.adiv[i]); } cur.adiv[i].shrink_to_fit(); } cur.cnt.clear(); cur.score = 0; for (int i = 0; i < N; ++i) for (int d : cur.adiv[i]) { int before = cur.cnt.get(d); cur.cnt.inc(d); if (before == 0) cur.score++; } }
State best = cur; cerr << "init score=" << best.score << "\n";
// SA parameters const double T0 = 1.0; const double T_end = 1e-5; const int CAND = 8; const ll LOG_INTERVAL = 200000; const ll RESTART_NO_IMPROVE = 1000000000LL; // 1e9 iterations const double time_limit = hours_per_run * 3600.0;
ll iter = 0; ll last_improve_iter = 0;
vector<vector<int>> cand_divs(CAND); vector<pair<int, int>> ftmp;
// outer infinite runs: each run uses a time_limit schedule, but program never exits for (;;) { auto run_start = chrono::high_resolution_clock::now(); // If starting a run from scratch, ensure cur is current best // We keep cur as is; but if run was restarted due to stuck, try_load_best later when needed
while (true) { ++iter; auto now = chrono::high_resolution_clock::now(); double elapsed = chrono::duration<double>(now - run_start).count(); if (elapsed >= time_limit) break; double progress = elapsed / time_limit; if (progress > 1.0) progress = 1.0; double T = T0 * pow(T_end / T0, progress);
int idx = rndint(0, N - 1); const vector<int> &divs_old = cur.adiv[idx]; int oldv = cur.a[idx];
// sample candidates (like original first version) and pick best candidate by delta int best_cand = oldv; ll best_cand_delta = LLONG_MIN; int cand_count = 0; for (int t = 0; t < CAND; ++t) { int v = random_value(); if (v == oldv) continue; auto it = value_to_idx.find(v); if (it != value_to_idx.end()) { cand_divs[cand_count] = predivs[it->second]; } else { factorize(v, ftmp); get_divisors(ftmp, cand_divs[cand_count]); } ll delta = compute_delta(cur, divs_old, cand_divs[cand_count]); if (delta > best_cand_delta) { best_cand_delta = delta; best_cand = v; } ++cand_count; if (cand_count >= CAND) break; } if (cand_count == 0) continue;
vector<int> new_divs; auto itb = value_to_idx.find(best_cand); if (itb != value_to_idx.end()) new_divs = predivs[itb->second]; else { factorize(best_cand, ftmp); get_divisors(ftmp, new_divs); }
ll delta = compute_delta(cur, divs_old, new_divs);
bool accept = false; if (delta >= 0) accept = true; else { double prob = exp((double)delta / max(1e-300, T)); // delta negative -> prob in (0,1) if (rnd01() < prob) accept = true; }
if (cur.cnt.need_rebuild()) { cur.cnt.rebuild(); cerr << "[counter rebuild] unique=" << cur.cnt.unique_cnt << " tombs=" << cur.cnt.tomb_cnt << "\n"; }
if (accept && best_cand != oldv) { ll oldscore = cur.score; del(cur, divs_old); cur.adiv[idx] = new_divs; cur.a[idx] = best_cand; add(cur, new_divs);
if (cur.score > best.score) { best = cur; last_improve_iter = iter; // write best to file ofstream fout(filename); for (int i = 0; i < N; i++) fout << best.a[i] << " "; fout << "\n"; fout.close(); cerr << "NEW BEST iter=" << iter << " score=" << best.score << "\n"; record(best); } else if (cur.score != oldscore) { last_improve_iter = iter; } }
if (iter % LOG_INTERVAL == 0) { cerr << "\titer=" << iter << " cur.score=" << cur.score << " last_imp=" << (iter - last_improve_iter) << " elapsed(s)=" << elapsed << "\n"; }
if (iter - last_improve_iter >= RESTART_NO_IMPROVE) { cerr << "[restart-stuck] iter=" << iter << " no improve for " << iter - last_improve_iter << ", reloading best.txt or using in-memory best\n"; bool loaded = try_load_best(cur); if (!loaded) { // fallback to in-memory best cur = best; } // reheat by resetting run start run_start = chrono::high_resolution_clock::now(); last_improve_iter = iter; // continue outer while (a fresh run) } } // end single run time_limit
// End of run due to time limit. Prepare next run: start from best, reheat. cerr << "[run complete] elapsed reached time_limit. best.score=" << best.score << " iter=" << iter << "\n"; // try to load best from disk (so external updates can be considered) bool loaded = try_load_best(cur); if (!loaded) { cur = best; } // continue next run automatically } // outer infinite return 0;}
```:::
## Expection
预期这道题的上限为 $24$ 万分,因为挖到后面很难跑出更优解了。
同时,等到量子超算出现后可以直接 ${(10^9)}^{1000}$ 枚举了,所以到时候比赛就该结束了。
挖到 $237200$ 往后就很慢了(可能是瓶颈),五六小时才多跑出来几分,所以目前很难超越榜一(他是啥,前沿、极光和富岳混进来了吗)。
~~同时为以后挖矿做准备。~~
## End
如果想要代码或者数据可以私信我,欢迎参与讨论。
> 如果你想要我的数据,我希望它们能遵循 CC BY-NC-SA 协议。简单说就是:> 你可以使用和研究它们。> 但请在使用时注明出处(来自我)。> 请不要用于商业盈利。> 如果你基于这些数据产生了新成果并想分享,也希望你能用同样的条款(CC BY-NC-SA)开放出来。>> 你可以使用和研究它们,但请在使用时注明出处(来自我),请不要用于商业盈利,如果你基于这些数据产生了新成果并想分享,也希望你能用同样的条款(CC BY-NC-SA)开放出来。>> 谢谢你的理解和尊重!
---
广告:
我们想自己办一个类 AHC 的启发式比赛,欢迎参与讨论。
快来参加第二届 `N Factors`:<https://www.luogu.com.cn/contest/285919>!