题意:
有一批糖果要由班长flymouse分发给班里的小朋友,给出m对数据u,v,w,表示第v个小朋友最多比第u个小朋友多w个,但flymouse与snoopy不和,所以在满足上述约束的条件下,flymouse要尽量比snoopy多。snoopy标号1,flymouse标号n
思路:
今天第一次学差分约束,感觉这道题目很简单,但是还是看得别人博客
有一批糖果要由班长flymouse分发给班里的小朋友,给出m对数据u,v,w,表示第v个小朋友最多比第u个小朋友多w个,但flymouse与snoopy不和,所以在满足上述约束的条件下,flymouse要尽量比snoopy多。snoopy标号1,flymouse标号n
思路:
以dis[1]=0,dis[i]表示相对dis[1]最多的糖果数。下面构造差分约束系统,对每一组数据u,v,w都是一条边(u,v,w),由题意约束条件为 d[v]-d[u]<=w,即 d[v]<=w+d[u] ,这与求最短路中的不等式 d[v]>w+d[u]被满足后则有 d[v]<=w+d[u] 相对应,所以求最短路满足约束条件且为最大值;最后用spfa(由于数据原因要用栈来实现)算法来求各个点的最短路程。dis[n]就是flymouse比snoopy最多的数目
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define maxn 299909
#define INF 0x3f3f3f3f
int dis[maxn],head[maxn],vis[maxn];
int q[maxn];
int n,m,cnt,st;
struct node
{
int v,w,next;
} edge[maxn];
void add(int u,int v,int w)
{
edge[cnt].v=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void SPFA()
{
int top=0;
memset(vis,0,sizeof(vis));
memset(dis,INF,sizeof(dis));
dis[st]=0;
vis[st]=1;
q[top++]=st;
while(top!=0)
{
int u=q[--top];
vis[u]=0;
for(int i=head[u]; i!=-1; i=edge[i].next)
{
if(dis[edge[i].v]>dis[u]+edge[i].w)
{
dis[edge[i].v]=dis[u]+edge[i].w;
if(!vis[edge[i].v])
{
vis[edge[i].v]=1;
q[top++]=edge[i].v;
}
}
}
}
}
int main()
{
int u,v,w;
while(~scanf("%d %d",&n,&m))
{
memset(head,-1,sizeof(head));
for(int i=0; i<m; i++)
{
scanf("%d %d %d",&u,&v,&w);
add(u,v,w);
}
st=1;
SPFA();
printf("%d\n",dis[n]);
}
return 0;
}
今天第一次学差分约束,感觉这道题目很简单,但是还是看得别人博客