题意:
n头牛编号为1到n,按照编号的顺序排成一列,每两头牛的之间的距离 >= 0。这些牛的距离存在着一些约束关系:1.有ml组(u, v, w)的约束关系,表示牛[u]和牛[v]之间的距离必须 <= w。2.有md组(u, v, w)的约束关系,表示牛[u]和牛[v]之间的距离必须 >= w。问如果这n头无法排成队伍,则输出-1,如果牛[1]和牛[n]的距离可以无限远,则输出-2,否则则输出牛[1]和牛[n]之间的最大距离。
分析:
约束条件:每两头牛的之间的距离 >= 0加入到差分约束的系统中去。整理成d[a]+w>=d[b],求最短路。当求最短路时,通常要把各点距离初始化为正无穷,求最短路,把各点距离逐渐减小,直到符合所有不等式。队列实现,而且有负权回路判断。
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
#define swap(t,a,b) (t=a,a=b,b=t)
using namespace std;
const int INF=0x3F3F3F3F;
const int V=1001;
const int E=20001;
int pnt[E],cost[E],nxt[E];
int e,head[V],dist[V];
bool vist[V];
int cnt[V];//入队列次数
int relax(int u,int v,int c){
if(dist[v]>dist[u]+c){
dist[v]=dist[u]+c;
return 1;
}
return 0;
}
void addedge(int u,int v,int c){
pnt[e]=v;
cost[e]=c;
nxt[e]=head[u];
head[u]=e++;
}
int SPFA(int src,int n){
int i;
memset(cnt,0,sizeof(cnt));
memset(vist,false,sizeof(vist));
for(i=1;i<=n;++i)
dist[i]=INF;
dist[src]=0;
queue<int> Q;
Q.push(src);
vist[src]=true;
++cnt[src];
while(!Q.empty()){
int u,v;
u=Q.front();
Q.pop();
vist[u]=false;
for(i=head[u];i!=-1;i=nxt[i]){
v=pnt[i];
if(relax(u,v,cost[i])&&!vist[v]){
Q.push(v);
vist[v]=true;
if((++cnt[v])>n)
return -1; //cnt[i]为入队列次数,判断是否存在负权回路 }
}
}
}
if(dist[n]==INF) return -2;
return dist[n];
}
int main(){
// freopen("in.txt","r",stdin);
int n,ml,md;
while(scanf("%d%d%d",&n,&ml,&md)!=EOF){
int i,a,b,c,t;
e=0;
memset(head,-1,sizeof(head));
for(i=0;i<ml;++i){
scanf("%d%d%d",&a,&b,&c);
if(a>b) swap(t,a,b);
addedge(a,b,c);
}
for(i=0;i<md;++i){
scanf("%d%d%d",&a,&b,&c);
if(a<b) swap(t,a,b);
addedge(a,b,-c);
}
printf("%d\n",SPFA(1,n));
}
return 0;
}