1075. 数字转换
题目链接
1075. 数字转换
如果一个数 \(x\) 的约数之和 \(y\)(不包括他本身)比他本身小,那么 \(x\) 可以变成 \(y\),\(y\) 也可以变成 \(x\)。
例如,\(4\) 可以变为 \(3\),\(1\) 可以变为 \(7\)。
限定所有数字变换在不超过 \(n\) 的正整数范围内进行,求不断进行数字变换且不出现重复数字的最多变换步数。
输入格式
输入一个正整数 \(n\)。
输出格式
输出不断进行数字变换且不出现重复数字的最多变换步数。
数据范围
\(1≤n≤50000\)
输入样例:
7
输出样例:
3
样例解释
一种方案为:\(4→3→1→7\)。
解题思路
树的直径,dfs
将每一个数当作一个节点,其父节点为其约数之和,因为一个数的约数之和是固定的,即其父节点只有一个,按父节点连向该节点,即一个节点只有一个入度,形成一个森林,然后在每棵树中寻找直径的最大值即可
枚举所有数的约数之和至少需要 \(O(nlogn)\) 的复杂度,则:
- 时间复杂度:\(O(nlogn)\)
代码
// Problem: 数字转换
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/description/1077/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
// %%%Skyqwq
#include
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
typedef long long LL;
typedef pair PII;
typedef pair PLL;
template bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
template void inline read(T &x) {
int f = 1; x = 0; char s = getchar();
while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
x *= f;
}
const int N=50005;
int n,s[N],d[N],res;
vector adj[N];
void dfs(int x,int fa)
{
for(int y:adj[x])
{
if(y==fa)continue;
dfs(y,x);
res=max(res,d[x]+d[y]+1);
d[x]=max(d[x],d[y]+1);
}
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
for(int j=2;j<=n/i;j++)
s[i*j]+=i;
for(int i=1;i<=n;i++)
if(s[i]