Time Limit: 1500MS | Memory Limit: 131072K |
---|
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.node
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?ios
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.markdown
Output one line with only the largest difference desired. The difference is guaranteed to be finite.ide
2 2
1 2 5
2 1 4oop
5ui
32-bit signed integer type is capable of doing all arithmetic.idea
POJ Monthly–2006.12.31, Semprspa
題意:發一些糖果,其中他們之間的糖果數目有必定的約束關係,u,v,w 表示a[v]<=a[u]+w,求a[n]-a[1]的最大值code
分析:典型的差分約束問題,不過在求最短路的過程當中,不能用queue,會超時(不造什麼緣由),用stack。three
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>
#include <queue>
#include <vector>
#include <stack>
#include <iostream>
#include <algorithm>
using namespace std;
const int MaxN = 31000;
const int MaxM = 151000;
const int INF = 0x3f3f3f3f;
typedef struct node
{
int v,w,next;
}Line ;
Line Li[MaxM];
int Head[MaxN],top;
int Dis[MaxN];
bool vis[MaxN];
int n,m;
void AddEdge(int u,int v,int w)
{
Li[top].v = v; Li[top].w = w;
Li[top].next = Head[u];
Head[u] = top++;
}
void SPFA()//求最短路
{
stack<int>Q;//用stack
memset(Dis,INF,sizeof(Dis));
memset(vis,false,sizeof(vis));
Dis[1] = 0 ;
vis[1]=true;
Q.push(1);
while(!Q.empty())
{
int u = Q.top();
Q.pop();
for(int i = Head[u];i!=-1;i = Li[i].next)
{
int v = Li[i].v;
if(Dis[v]>Dis[u]+Li[i].w)
{
Dis[v] = Dis[u]+Li[i].w;
if(!vis[v])
{
vis[v]=true;
Q.push(v);
}
}
}
vis[u] = false;
}
}
int main()
{
int u,v,w;
while(~scanf("%d %d",&n,&m))
{
memset(Head,-1,sizeof(Head));
top = 0;
for(int i=0;i<m;i++)
{
scanf("%d %d %d",&u,&v,&w);
AddEdge(u,v,w);
}
SPFA();
printf("%d\n",Dis[n]-Dis[1]);
}
return 0;
}