Center Street(最短路变形)

版权声明:本文章未经博主允许不得转载 https://blog.csdn.net/qq_42217376/article/details/89554092

链接:https://ac.nowcoder.com/acm/contest/877/I
来源:牛客网——黑龙江大学程序设计竞赛(重现赛)

  此题的思路主要来源于最短路Folyd,我们刚开始知道dp[0]=0,dp[2]=1(dp[i]表示1到i的最短距离),我们可以对每个数的倍数进行枚举(至今不理解为什么不超时),看是否能够更新当前的最短路.

#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;

typedef long long LL;
const LL inf=0x3f3f3f3f3f3f3f3f;
const int Max_n=5e5+10;
LL dp[Max_n];

int main(){
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        dp[i]=inf;
    dp[1]=0;dp[2]=1;
    for(int i=1;i<=n;i++){
        for(int j=i;j<=n;j+=i){
            dp[j]=min(dp[j],dp[i]+1LL*(j-i)*(j-i));
        }
    }
    for(int i=1;i<n;i++)
        printf("%lld ",dp[i]);
    printf("%lld\n",dp[n]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42217376/article/details/89554092