由于剩下 个节点中要有一条长度为 的路径,所以有 ,所以有 。
因此题目变为要求一条从 到 的简单路径,满足经过的节点数 满足 ,并使其边权和最短。
注意到 ,所以考虑动态规划。
设 为从 到 经过恰好经过 个节点的最小边权和。对于每个状态,有取或不取当前节点。于是就有状态转移方程:
于是就得出代码,枚举 ,然后再枚举节点和其边。时间复杂度为 。
AC Code:
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=505;
const int INF=1e18;
int n,m;
vector< pair<int,int> > G[maxn];
int f[maxn][maxn];
signed main(){
scanf("%lld%lld",&n,&m);
for(int i=1;i<=m;++i){
int u,v,w;
scanf("%lld%lld%lld",&u,&v,&w);
G[u].push_back({v,w});
}
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j) f[i][j]=INF;
f[1][1]=0;
for(int step=1;step<=n/2;++step){
for(int u=1;u<=n;++u){
if(f[u][step]==INF) continue;
for(auto e:G[u]){
int v=e.first,w=e.second;
f[v][step+1]=min(f[v][step+1],f[u][step]+w);
}
}
}
int ans=INF;
for(int i=1;i<=n/2;++i) ans=min(ans,f[n][i]);
if(ans==INF) cout<<-1;
else cout<<ans;
return 0;
}