最长路(拓扑排序)
本题可以先用拓扑排序确定遍历的顺序,在用简单的动态规划求最长路(拓扑排序保证了此时的状态一定可以从以前的状态转移过来)
拓扑排序+简单dp:
#include<iostream>
#include<string>
#include<string.h>
#define ri register int
using namespace std;
const int N=2e3,M=5e4+100;
struct wyx{
int to,next,w;
}edges[M];
int head[N],q[N],d[N],dp[N],dd[N];
int tot,n,m;
void add(ri u,ri v,ri w){
edges[tot].to=v,edges[tot].next=head[u],edges[tot].w=w;
head[u]=tot++;
d[v]++;
dd[u]++;
return;
}//链式前向星存图
bool topsort(){
ri ta=-1,he=0;
for(ri i=1;i<=n;i++){
if(d[i]==0){
q[++ta]=i;
}
}
while(he<=ta){
ri t=q[he++];
for(ri i=head[t];i!=-1;i=edges[i].next){
ri j=edges[i].to;
d[j]--;
if(d[j]==0){
q[++ta]=j;
}
}
}//拓扑排序
return ta==n-1;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
memset(head,-1,sizeof head);
cin>>n>>m;
for(ri i=1;i<=n;i++){//保证一定是从1为起点的
dp[i]=-1001000;//防止从别的点拓展出更长的边
}
dp[1]=0;
ri u,v,w;
for(ri i=1;i<=m;i++){
cin>>u>>v>>w;
add(u,v,w);
}
if(topsort()){//用拓扑排序原因:1.有向无环图
for(ri i=0;i<n;i++){// 2.保证从前往后遍历,避免dp时无法从前面的状态转移过来
ri t=q[i];
for(ri j=head[t];j!=-1;j=edges[j].next){
ri to=edges[j].to,w=edges[j].w;
dp[to]=max(dp[to],w+dp[t]);//通过动态规划求最长路
}
}
if(dp[n]<-100000) cout<<-1<<endl;
//特判一下无法到达终点的情况
else cout<<dp[n]<<endl;
}else{
cout<<-1<<endl;
}
return 0;
}