Luo Gu P1807 longest road _NOI Guide 2010 increase (07)

Title Description

Let G with n vertices directed acyclic graph, each vertex in the Code G 1 to n, and when G is an edge in when i <j. Provided for the length of the side w (i, j), designed to make the algorithm calculates the longest path between G <1, n> FIG.

Input Format

The first line of the input file longest.in two integers m and n, there are n vertices represent edges and m, m next row per line in three integers a, b, V (from point a to point b represents there point sides, of side length v).

Output Format

Output file longest.out, an integer, i.e., the longest path between 1 to n. If there is no communication between 1 to n, outputs -1.

 

Solution: Because there is a negative right side, so SPFA seeking longest road can be.

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<queue>
 6 #define maxn 1505
 7 #define INF 0x3ffff
 8 
 9 using namespace std;
10 
11 struct node
12 {
13     int ed,len,nxt;
14 };
15 node edge[50005];
16 int first[maxn],dis[maxn],cnt,n,m;
17 bool vis[maxn];
18 
19 inline void add_edge(int s,int e,int d)
20 {
21     cnt++;
22     edge[cnt].ed=e;
23     edge[cnt].len=d;
24     edge[cnt].nxt=first[s];
25     first[s]=cnt;
26     return;
27 }
28 
29 queue <int> q;
30 inline void spfa(int st)
31 {
32     for(int i=1;i<=n;i++)
33         vis[i]=false,dis[i]=-INF;
34     q.push(st); vis[st]=true;
35     dis[st]=0;
36     while(!q.empty())
37     {
38         int p=q.front(); q.pop();
39         vis[p]=false;
40         for(register int i=first[p];i;i=edge[i].nxt)
41         {
42             int e=edge[i].ed;
43             int d=edge[i].len;
44             int newd=dis[p]+d;
45             if(newd>dis[e])
46             {
47                 dis[e]=newd;
48                 if(!vis[e]) q.push(e);
49             }
50         }
51     }
52     return;
53 }
54 
55 int main()
56 {
57     scanf("%d%d",&n,&m);
58     for(register int i=1;i<=m;i++)
59     {
60         int s,e,d;
61         scanf("%d%d%d",&s,&e,&d);
62         add_edge(s,e,d);
63     }
64     spfa(1);
65     if(dis[n]==-INF) printf("-1\n");
66     else printf("%d",dis[n]);
67     return 0;
68 }

 

Guess you like

Origin www.cnblogs.com/Hoyoak/p/11427477.html
Recommended