3169 Layout

简单的差分约束

看错成一个图,dis[B]-dis[A]<=w,或者dis[B]-dis[A]>=W,然后求出图的最短距离,用bellman-ford算法就可以了

判断图是否有负环,输出-1,否则判断n和1是否可达,如果不行输出-2.否则输出最短距离。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
using namespace std;
const int N =1010;
int n,ml,md;
struct node{
int u,v,w;
}edge[N*10];
int dis[N];
const int INF = 999999;
bool bellford(){
for(int i = 1;i<=n;i++)dis[i] = INF;
dis[1] = 0;
for(int i = 0;i<n;i++)
for(int i = 0;i<md+ml;i++){
if(dis[edge[i].u]!=INF && dis[edge[i].v]>dis[edge[i].u]+edge[i].w)dis[edge[i].v] = dis[edge[i].u]+edge[i].w;
}
for(int i = 0;i<md+ml;i++)if(dis[edge[i].u]!=INF && dis[edge[i].v]>dis[edge[i].u]+edge[i].w)return false;
return true;
}
int main()
{
scanf("%d%d%d",&n,&ml,&md);
for(int i = 0;i<ml;i++){
scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
}
int u,v,w;
for(int i = 0;i<md;i++){
scanf("%d%d%d",&u,&v,&w);
edge[i+ml].u = v;
edge[i+ml].v = u;
edge[i+ml].w = -w;
}
if(bellford()){
if(dis[n]!=INF)printf("%d\n",dis[n]);
else printf("-2");
}else {
printf("-1\n");
}
return 0;
}

你可能感兴趣的:(算法,layout,ini)