洛谷 1807 最長路 SPFA 解題報告

題目描述

設G爲有n個頂點的有向無環圖,G中各頂點的編號爲1到n,且當爲G中的一條邊時有i < j。設w(i,j)爲邊的長度,請設計算法,計算圖G中<1,n>間的最長路徑。

輸入輸出格式

輸入格式:

輸入文件longest.in的第一行有兩個整數n和m,表示有n個頂點和m條邊,接下來m行中每行輸入3個整數a,b,v(表示從a點到b點有條邊,邊的長度爲v)。

輸出格式:

輸出文件longest.out,一個整數,即1到n之間的最長路徑.如果1到n之間沒連通,輸出-1。

輸入輸出樣例

輸入樣例#1:

2 1
1 2 1

輸出樣例#1:

1

說明

20%的數據,n≤100,m≤1000

40%的數據,n≤1,000,m≤10000

100%的數據,n≤1,500,m≤50000,最長路徑不大於10^9

思路

最長路,建負邊然後最短路取負數

代碼

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
const int N=1000+5;
const int INF=0x3f3f3f3f;
int head[N],flag[N],dis[N];
int num=0,n,m;
queue<int> q;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
struct edge
{
    int u,v,next;
    int w;
}ed[2*N*N];
void build(int u,int v,int w)
{
    ed[++num].u=u;
    ed[num].v=v;
    ed[num].w=w;
    ed[num].next=head[u];
    head[u]=num;
}
int SPFA()
{
    memset(dis,INF,sizeof(dis));
    memset(flag,0,sizeof(flag));
    flag[1]=1;dis[1]=0;
    q.push(1);
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        flag[u]=0;
        for (int i=head[u];i!=-1;i=ed[i].next)
        {
            int v=ed[i].v;
            if (dis[u]+ed[i].w<dis[v])
            {
                dis[v]=dis[u]+ed[i].w;
                if (!flag[v])
                {
                    flag[v]=1;
                    q.push(v);
                }
            }
        }
    } 
    return -dis[n];
}
int main()
{
    num=0;
    memset(head,-1,sizeof(head));
    n=read();m=read();
    for (int i=1;i<=m;i++)
    {
        int u=read(),v=read(),w=read();
        build(u,v,-w);
    }
    int ans=SPFA();
    if (ans==-INF) printf("-1\n");
    else printf("%d",ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章