# POJ 3159 Candies （图论，差分约束系统，最短路）

### 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 A, B 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.

2 2
1 2 5
2 1 4

5

## 解决思路

$D[B]-D[a]>=c$

$D[a]+c<=D[b]$

（只要题中说明了不会出现负环，就可以用spfa+stack，其效率高于spfa+queue）

## 代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<stack>
using namespace std;

const int maxN=30001;
const int maxM=150001;
const int inf=2147483647;

class Graph//把图的相关内容封装到Graph里，方便编写
{
private:
int cnt;
stack<int> S;
int instack[maxN];//使用stack而不是queue作为spfa的容器
int V[maxM];
int W[maxM];
int Next[maxM];
public:
int Dist[maxN];
void init()
{
memset(Next,-1,sizeof(Next));
cnt=0;
}
{
cnt++;
V[cnt]=v;
W[cnt]=w;
}
void spfa()
{
memset(Dist,127,sizeof(Dist));
memset(instack,0,sizeof(instack));
while (!S.empty())
S.pop();
Dist=0;
instack=1;
S.push(1);
do
{
int u=S.top();
S.pop();
instack[u]=0;
{
if (Dist[V[i]]>Dist[u]+W[i])
{
Dist[V[i]]=Dist[u]+W[i];
if (instack[V[i]]==0)
{
S.push(V[i]);
instack[V[i]]=1;
}
}
}
}
while (!S.empty());
}
};

int n,m;
Graph G;

int main()
{
while (cin>>n>>m)
{
G.init();
for (int i=1;i<=m;i++)
{
}
G.spfa();
cout<<G.Dist[n]<<endl;
}
return 0;
}

{
int x=0;
int k=1;
char ch=getchar();
while (((ch>'9')||(ch<'0'))&&(ch!='-'))
ch=getchar();
if (ch=='-')
{
k=-1;
ch=getchar();
}
while ((ch>='0')&&(ch<='9'))
{
x=x*10+ch-48;
ch=getchar();
}
return x*k;
}

posted @ 2017-07-24 15:06  SYCstudio  阅读(216)  评论(0编辑  收藏