查分约束好题,关键在于转化!
#include<iostream>
using namespace std;
#define MAX 20020
#define INF 999999
struct Node{
int u,v;
int val;
}node[MAX];
int nv,ne,start;
int dist[MAX];
int bellman_DC()
{
int i,j,tmp,tag;
for(i=1;i<=nv;++i)
dist[i] = INF;
dist[start] = 0;
for(i=1;i<nv;++i)
{
tag = 0;
for(j=1;j<=ne;++j)
{
tmp = dist[node[j].u]+node[j].val;
if(tmp<dist[node[j].v])
{
dist[node[j].v] = tmp;
tag = 1;
}
}
if(tag == 0)
return 0;
}
for(i=1;i<=ne;++i)
if(dist[node[i].v]>dist[node[i].u]+node[i].val)
return 1;
return 0;
}
int main()
{
int i,j,a,b,flag,m1,m2,val,index;
while(scanf("%d%d%d",&nv,&m1,&m2)!=EOF)
{
index = 0;
ne = m1+m2;
for(i=1;i<=m1;++i)
{
++index;
scanf("%d%d%d",&a,&b,&val);
node[index].u = a;
node[index].v = b;
node[index].val = val;
}
for(i=1;i<=m2;++i)
{
++index;
scanf("%d%d%d",&a,&b,&val);
node[index].u = b;
node[index].v = a;
node[index].val = -val;
}
start = 1;
flag = bellman_DC();
if(flag == 1)
printf("-1\n");
else if(dist[nv]==INF)
printf("-2\n");
else
printf("%d\n",dist[nv]);
}
return 0;
}
using namespace std;
#define MAX 20020
#define INF 999999
struct Node{
int u,v;
int val;
}node[MAX];
int nv,ne,start;
int dist[MAX];
int bellman_DC()
{
int i,j,tmp,tag;
for(i=1;i<=nv;++i)
dist[i] = INF;
dist[start] = 0;
for(i=1;i<nv;++i)
{
tag = 0;
for(j=1;j<=ne;++j)
{
tmp = dist[node[j].u]+node[j].val;
if(tmp<dist[node[j].v])
{
dist[node[j].v] = tmp;
tag = 1;
}
}
if(tag == 0)
return 0;
}
for(i=1;i<=ne;++i)
if(dist[node[i].v]>dist[node[i].u]+node[i].val)
return 1;
return 0;
}
int main()
{
int i,j,a,b,flag,m1,m2,val,index;
while(scanf("%d%d%d",&nv,&m1,&m2)!=EOF)
{
index = 0;
ne = m1+m2;
for(i=1;i<=m1;++i)
{
++index;
scanf("%d%d%d",&a,&b,&val);
node[index].u = a;
node[index].v = b;
node[index].val = val;
}
for(i=1;i<=m2;++i)
{
++index;
scanf("%d%d%d",&a,&b,&val);
node[index].u = b;
node[index].v = a;
node[index].val = -val;
}
start = 1;
flag = bellman_DC();
if(flag == 1)
printf("-1\n");
else if(dist[nv]==INF)
printf("-2\n");
else
printf("%d\n",dist[nv]);
}
return 0;
}