POJ-3159-Candies(SPFA+模拟栈)

来源:互联网 发布:网络翻墙什么意思 编辑:程序博客网 时间:2024/04/28 17:23

Description

During the kindergarten days, flymouse was the monitor of his class. Occasionally the head-teacher brought the kids of flymouse’s class a large bag of candies and had flymouse distribute them. All the kids loved candies very much and often compared the numbers of candies they got with others. A kid A could had the idea that though it might be the case that another kid B was better than him in some aspect and therefore had a reason for deserving more candies than he did, he should never get a certain number of candies fewer than B did no matter how many candies he actually got, otherwise he would feel dissatisfied and go to the head-teacher to complain about flymouse’s biased distribution.

snoopy shared class with flymouse at that time. flymouse always compared the number of his candies with that of snoopy’s. He wanted to make the difference between the numbers as large as possible while keeping every kid satisfied. Now he had just got another bag of candies from the head-teacher, what was the largest difference he could make out of it?

Input

The input contains a single test cases. The test cases starts with a line with two integers N and M not exceeding 30 000 and 150 000 respectively. N is the number of kids in the class and the kids were numbered 1 through N. snoopy and flymouse were always numbered 1 and N. Then follow M lines each holding three integers AB and c in order, meaning that kid A believed that kid B should never get over c candies more than he did.

Output

Output one line with only the largest difference desired. The difference is guaranteed to be finite.

Sample Input

2 21 2 52 1 4

Sample Output

5


思路:用SPFA+模拟队列超时了,改成栈就AC了。。。

#include <cstdio>#include <stack>#define INF 99999999using namespace std;struct E{int v,w;}e[150000];stack<int>s;int d[30001],first[30001],next[150000];bool ins[30001];int main(){    int n,m,i,u,v,w;    scanf("%d%d",&n,&m);    for(i=1;i<=n;i++) ins[i]=0,d[i]=INF,first[i]=-1;    for(i=0;i<m;i++)    {        scanf("%d%d%d",&u,&v,&w);        e[i].v=v;        e[i].w=w;        next[i]=first[u];        first[u]=i;    }    s.push(1);    d[1]=0;    while(!s.empty())    {        u=s.top();        s.pop();        ins[u]=0;        for(i=first[u];i>=0;i=next[i])        {            if(d[e[i].v]>d[u]+e[i].w)            {                d[e[i].v]=d[u]+e[i].w;                if(!ins[e[i].v])                {                    s.push(e[i].v);                    ins[e[i].v]=1;                }            }        }    }    printf("%d\n",d[n]);}


43 0