Codeforces - Journey

题目链接:Codeforces - Journey


令dp[x][i] 为1到点x,经过i个点的最短距离。

然后DAG上面dp即可。


AC代码:

#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=5e3+10;
int n,m,k,deg[N],dp[N][N],res,pre[N][N];
int head[N],nex[N],to[N],w[N],tot;
inline void add(int a,int b,int c){
	to[++tot]=b; nex[tot]=head[a]; w[tot]=c; head[a]=tot;
}
void Top(){
	queue<int> q;	dp[1][1]=0;
	for(int i=1;i<=n;i++)	if(!deg[i])	q.push(i);
	while(q.size()){
		int u=q.front();	q.pop();
		for(int i=head[u];i;i=nex[i]){
			if(--deg[to[i]]==0)	q.push(to[i]);
			for(int j=1;j<=n;j++)	if(dp[u][j]+w[i]<dp[to[i]][j+1]){
				dp[to[i]][j+1]=dp[u][j]+w[i];
				pre[to[i]][j+1]=u;
			}
		}
	}
}
void dfs(int x,int y){
	if(x&&y)	dfs(pre[x][y],y-1);
	if(x)	printf("%d ",x);
}
signed main(){
	cin>>n>>m>>k;	memset(dp,0x3f,sizeof dp);
	for(int i=1,a,b,c;i<=m;i++)	cin>>a>>b>>c,add(a,b,c),deg[b]++;
	Top();
	for(int i=1;i<=n;i++)	if(dp[n][i]<=k)	res=i;
	cout<<res<<'\n';	dfs(n,res);
	return 0;
}
发布了725 篇原创文章 · 获赞 244 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_43826249/article/details/104855897