跳到正文

题解

题解:数上的树

gyh20约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年6月14日
更新
2026年6月14日
篇幅
约 3 分钟
获赞
9
题目
P7091

版本

  1. v1当前

算法 11:搜索。

搜索树的形态,可过 Subtask1 期望得分 55。

接下来需要一个结论:

虽然以 nn 为根的子树答案不确定,但节点个数是确定的,因为其中包含多少个点只和质因子个数有关。

算法 22:DP。

设 fif_i 表示以 ii 为根的最小值,则 fi=min⁡(fj+fi/j[j∣i])f_i=\min(f_j+f_{i/j}[j|i]),如果用 n\sqrt n 的检验质因子可以获得 4545 分。

算法 33:Subtask4

贪心,发现每次把最大质因子分出去一定最优,这样能使得当前节点的贡献最小且其他子树贡献最小,结合之前算法可获得 6565 分。

算法 44:

继续沿用算法 22 的方法,考虑优化转移。

发现每一个数的因数一定是 nn 的因数,所以检验因数时只用判断 nn 的因数即可。

nn 的因数至多有一万多个,再加上每次只用枚举到根号,所以经测验是可过的,标程最大的点 1s1s 能出解。

常数优化:mapmap 很慢,建议离散化用数组维护。

算法 55:

用 Pollard-Rho 优化分解,可能会被卡,但由于这是 CSP 难度的模拟赛,所以不做延伸。

C++
#include<cstdio>
#include<algorithm>
#include<map>
#include<cmath>
using namespace std;
#define re register
long long n,pri[1000002],num[1000002],dp[1000002];
map<long long,bool>vis;
map<long long,int>pos;
int cntt,cnttt,m,cnt;
inline int dfs(re long long x){
	if(pos.count(x))return pos[x];
	re int xx=sqrt(x);pos[x]=++cntt;re int y=cntt;
	dp[y]=4e18;
	for(re int i=1;i<=cnt&&pri[i]<=xx;++i){++cnttt;
		if(x%pri[i]==0){
			re int ls=dfs(pri[i]),rs=dfs(x/pri[i]);
			num[y]=num[ls]+num[rs]+1;
			dp[y]=min(dp[y],(num[ls]+1)*(num[rs]+1)*x+dp[ls]+dp[rs]);
		}
	}
	if(!num[y])num[y]=1,dp[y]=x;
//	printf("%lld %d\n",x,y);
	if(vis.count(x))dp[y]=4e18;
	return y;
}
signed main(){
//	freopen("a30.in","r",stdin);
//	freopen("a30.out","w",stdout);
	scanf("%lld%d",&n,&m);
	re long long x;
	for(re int i=1;i<=m;++i)scanf("%lld",&x),vis[x]=1;
	if(vis.count(n))return puts("-1"),0;
	re int xx=sqrt(n);
	for(re int i=2;i<=xx;++i)if(n%i==0)pri[++cnt]=i;
	dfs(n);
	printf("%lld",dp[pos[n]]==4e18?-1:dp[pos[n]]);
}
原文
存档评论5 条抓取于