最长路

到现在才写最长路,我真是太菜了

题目链接

P1807 最长路_NOI导刊2010提高(07)

思路

拓扑排序+dp

f[i]表示到i点的最长路,然后转移就不用写了,看代码吧

代码

#include<bits/stdc++.h>
#include<queue>
using namespace std;
const int N=2019;//点
const int M=50001;//边
queue<int>q;//拓扑排序用的队列
int ru[N] ,head[M], cnt ,f[N];
struct node {
	int u,v,Next,w;
} e[M];
int n,m;
void add(int x,int y,int z) {
	e[++cnt].u=x;
	e[cnt].v=y;
	e[cnt].w=z;
	e[cnt].Next=head[x];
	head[x]=cnt;
}
int main() {
	memset(f,-0x3f3f3f,sizeof(f));
	cin>>n>>m;
	for(int i=1; i<=m; ++i) {
		int x,y,z;
		scanf("%d%d%d",&x,&y,&z);
		add(x,y,z);
		ru[y]++;
	}
	f[1]=0;
	for(int i=1; i<=n; ++i) {
		if(ru[i]==0) q.push(i);
	}
	while(!q.empty()) {
		int x=q.front();
		q.pop();
		for(int i=head[x]; i; i=e[i].Next) {
			ru[e[i].v]--;
			f[e[i].v]=max(f[e[i].v],f[x]+e[i].w);
			if(ru[e[i].v]==0) q.push(e[i].v);
		}
	}
	if(f[n]<0) {
		printf("%d",-1);
		return 0;
	}
	printf("%d",f[n]);
	return 0;
}
原文地址:https://www.cnblogs.com/pyyyyyy/p/11332895.html