zoukankan      html  css  js  c++  java
  • 最长路

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

    题目链接

    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;
    }
    
  • 相关阅读:
    1010考试T1
    P5631 最小mex生成树 分治 并查集
    P4366 [Code+#4]最短路 建图 最短路
    P1654 OSU! 期望概率DP
    7.26集训
    7.25集训
    7.23集训
    7.22集训
    7.21test
    7.12test
  • 原文地址:https://www.cnblogs.com/pyyyyyy/p/11332895.html
Copyright © 2011-2022 走看看