Time Limit: 1500MS | Memory Limit: 131072K | |
Total Submissions: 25776 | Accepted: 7033 |
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, Band 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 2 1 2 5 2 1 4
Sample Output
5
用队列会超时,用数组模拟栈
题意:每个人都会分得糖果,要求两个孩子之间的糖果差距应该尽可能的小,输入数据a b c 表示b孩子的糖果最多比a多c个,求n孩子最多比第一个孩子最多多少个
题解:由题意可知b-a<=c;满足此公式,要求找到起点到终点的最少的差距,可以转化为最短路问题
差分约束!点我
#include<stdio.h> #include<string.h> #define MAX 160000 #define INF 0x3f3f3f #include<queue> using namespace std; int head[MAX]; int n,m,ans; int dis[MAX],vis[MAX]; int stack[MAX]; struct node { int u,v,w; int next; }edge[MAX]; void add(int u,int v,int w) { edge[ans].u=u; edge[ans].v=v; edge[ans].w=w; edge[ans].next=head[u]; head[u]=ans++; } void init() { ans=0; memset(head,-1,sizeof(head)); } void getmap() { int i,j; int a,b,c; for(i=1;i<=m;i++) { scanf("%d%d%d",&a,&b,&c); add(a,b,c); } } void spfa(int sx) { int i,j; int topp=0; queue<int>q; memset(vis,0,sizeof(vis)); for(i=1;i<=n;i++) dis[i]=INF; vis[sx]=1; dis[sx]=0; stack[topp++]=sx; while(topp!=0) { int u=stack[topp-1]; topp--; vis[u]=0; for(i=head[u];i!=-1;i=edge[i].next) { int top=edge[i].v; if(dis[top]>dis[u]+edge[i].w) { dis[top]=dis[u]+edge[i].w; if(!vis[top]) { vis[top]=1; stack[topp++]=top; } } } } printf("%d ",dis[n]); } int main() { while(scanf("%d%d",&n,&m)!=EOF) { init(); getmap(); spfa(1); } return 0; }