N Factor 做题记录
偶然发现了一个洛谷上的个人公开赛,长得很像 AHC,加上我闲,于是就做了。
其实是上次 AHC 打得很烂,表现分才青。
题意很简单:构造 个 以内的正整数,让它们的因数集合的大小尽可能大。
本人较菜,目前 。
大部分代码均由 GTP-5 Free / Grok 4 Fast 赞助,所以不放了。
广告:
我们想自己办一个类 AHC 的启发式比赛,欢迎参与讨论。
快来参加第二届 N Factors:https://www.luogu.com.cn/contest/285919!
侵删。
Prepare
一些链接:
Part 1
下面这部分是我 分钟写完凑数的。
Naive
输出 ,简单 分,不知道这个分数的人想干什么。
猜你不想要
for i in range(1,1001): print(i,end=' ')Common
脑抽了,打了一个随机选质数跑高合成数,只有 万分,甚至不如乱搞。
太丢人了,代码不放了。
Plus
所以用现成的高合成数。
观察发现 以内的最大高合成数是 ,输出祂的倍数。
分
cnt=0
for i in range(10**9//720720*720720,0,-720720):
print(i,end=' ')
cnt+=1
if cnt==1000:breakPart 2
感谢 YYZ1208 提供的思路。
Naive
考虑朴素构造,挑选若干个高合成数,把他们扔上去,没试过。
Common
挑选一个合适的基,有尽量多的因数(高合成数),然后输出它的 倍。
估计 万分,是的,不如乱搞。
Plus
改为输出它的质数倍,避免重复,有 万分。
具体的:
- 第 个质数是 ,可以在数字帝国查看 https://zh.numberempire.com/1000#:~:text=1009-,1000th%20%E8%B4%A8%E6%95%B0,-7919。
- 你可以选择小于等于 的高合成数,在 OEIS 上看,是 ,所以输出它的质数倍。
理论得分:。
Extra
发现选质数倍很蠢,因为你选一个 就等效选了 ,因此可以改乘小高合成数。
实现的精细一点,可以获得 YYZ1208 的 万分。
代码别找我,找 YYZ1208 吧。
Part 3
不知道是谁跟我说直接跑贪心,每次选一个使当前分数最大的选就有 万多分,所以这样很有前途。
考虑随机化乱搞。
Naive
直接强上,没试过。
具体来说,就是随机修改 个数中的某一个,然后计算贡献。
- 如果你打的是模拟退火:
- 如果更劣,以一定概率接受;
- 否则直接接受。
- 如果你打的是爬山算法:
- 只有更优才接受。
爬山的小优化
- 如果连续很多次没有更优,说明陷入局部最优解,随机修改若干个重跑;
- 可以每隔固定迭代次数记录到文件,下次开跑时直接读文件。
Common
观察刚刚获得的输出,发现,所有数都是 的倍数,大胆猜测,每个数都是 的倍数的情况最优,问题缩减到原来的 ,跑起来嘎嘎快。
Plus
观察发现,一个数小于 可以乘上 ,更不劣。
同时观察发现,每个数都是 的倍数的情况最优,所以跑的更快了。
同时直接大胆猜测(其实还是观察发现),选中的数最大质因子不会很大,所以扔掉所有质因子大于第 个质数的数。
我们期望每个数的因数尽可能多,可以提前打一个筛,把所有不符合的数筛掉,一共发现只有 个,所以更容易跑出更优解。
Extra
可以利用刚刚筛出来的数的性质,跑出来前 个质数,试除法就能光速因式分解。
不妨借鉴预处理的思路,直接把 个数的因数都晒出来,需要时直接调用就行了。
实测快了不止一点,同时可以手打哈希表,可以从 Library Checker 上拷一个最快的。
Code
给出主函数:
爬山
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
sieve();
prepare();
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 的模拟退火跑得分数很高,因为模拟退火不容易卡局部最优解。
Common
直接敲诈祂,搞到了祂的代码和数据。
祂的数据是啥啊,随便爬山挖一挖就多了 分。
祂的模拟退火是啥啊,打的这么垃圾。
考虑自己打一个,参数已经有人调好了,对着爬山改就行了。
Plus
由于爬山是每次改一个数,真的很难跳出局部最优解,观察某人的实现,祂是每次改修改 个数,每次以极小概率接受更劣解。
至于祂的温度是怎么打的,没看懂,照搬即可。
Extra
模拟退火单独一个跑起来还是太费劲了,所以我们考虑细节上优化实现。
具体来说,我们希望多线程一起跑,最大效率利用 CPU 资源挖矿解。
所以我们可以这样实现,启动后从 best.txt 里读取最优解,然后开跑。
如果跑出更优解,就选择记录下来,存到 best.txt,但这是就会有一个问题,如果一个程序从 分先跑出了 分,然后另一个跑出了 分,这样 best.txt 就会被更差的覆盖了。
所以你可以打一个多线程来控制,防止误写,或者写的时候判断一下。
但是我选择另一种方法,直接写进对应分数的文件里,即跑出 分时写进 102.txt,跑出 分时写进 101.txt,这样即使 best 被覆写,也可以保留不同的分数。
这样做还有一个优点,可以获得不同局部的最优解,丰富样本的多样性。
当然可以拼上爬山的小优化,如果跑了很多遍都没有更优解,就直接读取 best.txt 重启(记得重启温度,但是我不知道某人的温度是怎么定的,所以没打)。
Code
同样只给出主函数,可以同时运行多个。
多开参照
本机是 Intel(R) Core(TM) i5-10500 CPU @ 3.10GHz, 核 线程,以下是实测表。
第一列表示开了几个,iters 表示迭代次数,每次测试皆跑 次迭代,取平均值。
1: 1*2000000 iters used 169.251s=84.625500s/M
2: 2*2000000 iters used 177.247s=44.311750s/M
3: 3*2000000 iters used 218.626s=36.437667s/M
4: 4*2000000 iters used 268.863s=33.607875s/M
5: 5*2000000 iters used 358.254s=35.825400s/M
6: 6*2000000 iters used 512.126s=42.677167s/M模拟退火
int 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
预期这道题的上限为 万分,因为挖到后面很难跑出更优解了。
同时,等到量子超算出现后可以直接 枚举了,所以到时候比赛就该结束了。
挖到 往后就很慢了(可能是瓶颈),五六小时才多跑出来几分,所以目前很难超越榜一(他是啥,前沿、极光和富岳混进来了吗)。
同时为以后挖矿做准备。
End
如果想要代码或者数据可以私信我,欢迎参与讨论。
如果你想要我的数据,我希望它们能遵循 CC BY-NC-SA 协议。简单说就是:
你可以使用和研究它们,但请在使用时注明出处(来自我),请不要用于商业盈利,如果你基于这些数据产生了新成果并想分享,也希望你能用同样的条款(CC BY-NC-SA)开放出来。
谢谢你的理解和尊重!
广告:
我们想自己办一个类 AHC 的启发式比赛,欢迎参与讨论。
快来参加第二届 N Factors:https://www.luogu.com.cn/contest/285919!