今天才知道差分约束这种神奇的东西
但三角不等式还是不熟 构造时错了很多次
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#include<limits.h>
struct edge{
int u,v,w;
}edges[500000];
int dist[1001];
int main()
{
int n,ml,md,m;
scanf("%d%d%d",&n,&ml,&md);
m=0;
for (int i=1;i<=ml;i++)
{
m++;
scanf("%d%d%d",&edges[m].u,&edges[m].v,&edges[m].w);
}
for(int i=1;i<=md;i++)
{
m++;
scanf("%d%d%d",&edges[m].v,&edges[m].u,&edges[m].w);
edges[m].w=-edges[m].w;
}
for (int i=0;i<=n;i++) dist[i]=INT_MAX;
dist[1]=0;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
if (dist[edges[j].u]!=INT_MAX && dist[edges[j].v]>dist[edges[j].u]+edges[j].w)
dist[edges[j].v]=dist[edges[j].u]+edges[j].w;
bool flag=true;
for (int j=1;j<=m;j++)
if (dist[edges[j].u]!=INT_MAX &&dist[edges[j].v]>dist[edges[j].u]+edges[j].w) flag=false;
if (!flag) printf("-1\n");
else if (dist[n]==INT_MAX) printf("-2\n");
else printf("%d\n",dist[n]);
return 0;
}
spfa
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#include<limits.h>
struct edge{
int u,v,w,next;
}edges[500000];
int dist[1001],h[500000],v[1001],edgeh[500000];
int main()
{
int n,ml,md,m;
scanf("%d%d%d",&n,&ml,&md);
m=0;
memset(edgeh,0,sizeof(edgeh));
for (int i=1;i<=ml;i++)
{
m++;
scanf("%d%d%d",&edges[m].u,&edges[m].v,&edges[m].w);
edges[m].next=edgeh[edges[m].u];
edgeh[edges[m].u]=m;
}
for(int i=1;i<=md;i++)
{
m++;
scanf("%d%d%d",&edges[m].v,&edges[m].u,&edges[m].w);
edges[m].w=-edges[m].w;
edges[m].next=edgeh[edges[m].u];
edgeh[edges[m].u]=m;
}
for (int i=0;i<=n;i++) dist[i]=INT_MAX;
dist[1]=0;
int l,r,x;
bool flag=true;
l=0;r=1;h[1]=1;
for (int i=1;i<=n;i++) v[i]=0;
while(l<=r && flag)
{
l++;
x=h[l];
v[x]=0;
for (int i=edgeh[x];i!=0;i=edges[i].next)
if (dist[x]!=INT_MAX && dist[edges[i].v]>dist[x]+edges[i].w){
dist[edges[i].v]=dist[x]+edges[i].w;
if (v[edges[i].v]==0){
v[edges[i].v]=1;
r++;
h[r]=edges[i].v;
}
}
if (l>=n*m) flag=false;
}
if (!flag) printf("-1\n");
else if (dist[n]==INT_MAX) printf("-2\n");
else printf("%d\n",dist[n]);
return 0;
}