题解 P1807 【最长路_NOI导刊2010提高(07)】

· · 题解

看c++拓扑排序没人发,我就来一发(滑稽)

做法:拓扑排序+DAG上dp

这题还算是水题,拓扑排序去掉入度为1的点,然后就可以用bfs来做dp了,转移方程也很明显:

dj=max(dj,di+wi,j)(i,j可达)

关于这题为什么要拓扑排序,好像是不做拓扑排序就会在dp的时候出各种问题。。

希望大家可以来我的博客看看^_^

下来贴代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
struct edge{
    int to,w;
    edge(int y,int l):to(y),w(l){}
};
int n,m;
vector<edge> G[1501];
int d[1501];
int du[1501];
void addedge(int x,int y,int l){
    G[x].push_back(edge(y,l));
    du[y]++;
}
void toposort(int s){
    queue<int> q;
    q.push(s);
    while(!q.empty()){
        int x=q.front();
        q.pop();
        for(int i=0;i<G[x].size();i++){
            edge &e=G[x][i];
            du[e.to]--;
            if(du[e.to]==0){
                q.push(e.to);
            }
        }
        G[x].clear();
    }
}
void bfs(int s){
    queue<int> q;
    q.push(s);
    while(!q.empty()){
        int x=q.front();
        q.pop();
        for(int i=0;i<G[x].size();i++){
            edge &e=G[x][i];
            if(d[x]+e.w>d[e.to]){
                d[e.to]=d[x]+e.w;
                q.push(e.to);
            }
        }
    }
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++){
        int x,y,l;
        scanf("%d%d%d",&x,&y,&l);
        addedge(x,y,l);
    }
    for(int i=2;i<=n;i++){
        if(du[i]==0){
            toposort(i);
        }
    }
    if(du[n]==0){
        printf("-1");
        return 0;
    }
    bfs(1);
    printf("%d",d[n]);
    return 0;
}