题目大意:
有n个人,m条信息,每条信息的格式是A B X,及B比A多X块糖,求第N个人比第一个人最多多几块。
注意:
1、虽然是最多多几块,但是开始差分约束用SPFA求解最短路来解决。
2、这里用SPFA时如果用STL里面的队列会超时,可以改作用栈来实现。
下面是代码:
#include <stdio.h>
#include <stack>
#include <string.h>
using namespace std;
struct node
{
int to,next,w;
} edge[150000];
int n,m,head[30005],dis[30005];
bool vis[30005];
void SPFA()
{
int i;
stack <int> q;
q.push(1);
vis[1]=true;
dis[1]=0;
while(q.size())
{
int t=q.top();
q.pop();
int p=head[t];
vis[t]=false;
while(p!=-1)
{
if(dis[edge[p].to]>dis[t]+edge[p].w)
{
dis[edge[p].to]=dis[t]+edge[p].w;
if(!vis[edge[p].to])
{
q.push(edge[p].to);
vis[edge[p].to]=true;
}
}
p=edge[p].next;
}
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
int i,x,y,w,cnt=0;
char c;
for(i=0; i<=n; i++)
{
head[i]=-1;
dis[i]=1<<30;
vis[i]=false;
}
for(i=0; i<m; i++)
{
scanf("%d%d%d",&x,&y,&w);
edge[cnt].to=y;
edge[cnt].w=w;
edge[cnt].next=head[x];
head[x]=cnt;
cnt++;
}
SPFA();
printf("%d\n",dis[n]);
}
return 0;
}