题目描述:
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?
输入:
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 one line with only the largest difference desired. The difference is guaranteed to be finite.
样例输入:
2 2
1 2 5
2 1 4
样例输出:
5
题目大意:
n个人,m个信息,每行的信息是3个数字,A,B,C,表示B比A多出来的糖果不超过C个,问你,n号人最多比1号人多几个糖果
思路:对应最短路模型,在松弛完最短路后则变为 d[v] <= d[u] + w ,转化为 d[v] - d[u] <= w,这个和上面的 B - A <= C 是相同的模式 , 因此建图的时候A和B连一条有向边 , 边权为C,以1为起点,n为终点跑一遍最短路即可
code:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;
typedef pair<int,int> P;
int head[30050];
int visit[30050];
const int inf=99999999;
int n,m;
struct node{
int v,w,next;
}edge[150005];
int cnt;
int d[30050];
int flag=0;
void add(int u,int v,int w)
{
edge[cnt].v=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt++;
}
int dijkstra()
{
priority_queue<P,vector<P> ,greater<P>> que;
memset(visit,0,sizeof(visit));
que.push(P(0,1));
fill(d,d+n+5,inf);
d[1]=0;
while(!que.empty())
{
P p=que.top();
que.pop();
int v=p.second;
if(d[v]<p.first)continue;
for(int i=head[v];i!=-1;i=edge[i].next)
{
int vv=edge[i].v;
if(d[vv]>d[v]+edge[i].w)
{
d[vv]=d[v]+edge[i].w;
que.push(P(d[vv],vv));
}
}
}
}
int main()
{
int dd;
scanf("%d%d",&n,&m);
memset(head,-1,sizeof(head));
cnt=0;
for(int i=0;i<m;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
}
dijkstra();
printf("%d\n",d[n]);
return 0;
}
感谢这题,让我总算是学会了邻接表
当然,这一道题可能使用的并非dijkstra,暂时先这么命名