Hdu 3592(差分约束)

poj 3592

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
#define ms(i,j) memset(i, j, sizeof i);
const int INF = 100000000;
const int MAXN = 1000 + 5;
struct edge
{
int u, v, c;
}e[MAXN*MAXN];
int en;
struct sysdc
{
int n;
vector<int> G[MAXN];
int dis[MAXN];
int vi[MAXN];
int cir[MAXN];
void init(int n)
{
en = 0;
this->n = n;
for (int i=1;i<=n;i++) G[i].clear();
}
int ins(int a, int b, int c)//add a-b<=c
{
en++;
e[en].u = b;
e[en].v = a;
e[en].c = c;
G[b].push_back(en);
}
int solve()
{
queue<int> q;
for (int i=2;i<=n;i++)
{
dis[i] = INF;
vi[i] = false;
cir[i] = 0;
}
dis[1] = 0; vi[1] = true; cir[1] = 1; q.push(1);
while (!q.empty())
{
int r = q.front(); q.pop();vi[r] = false;
for (int i=0;i<G[r].size();i++)
{
edge p = e[G[r][i]];
if (dis[p.v]>dis[p.u]+p.c)
{
dis[p.v] = dis[p.u]+p.c;
if (!vi[p.v])
{
cir[p.v]++;
if (cir[p.v]>n) return false;
vi[p.v] = true;
q.push(p.v);
}
}
}
}
return true;
}
}sdc;
int n, X, Y;
void init()
{
scanf("%d%d%d", &n ,&X, &Y);
sdc.init(n);
}
void solve()
{
for (int i=1;i<=X;i++)//friend
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
if (a>b) swap(a,b);
sdc.ins(b,a,c);
}
for (int i=1;i<=Y;i++)//hate
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
if (a>b) swap(a,b);
sdc.ins(a,b,-c);
}
if (sdc.solve())
{
if (sdc.dis[n]==INF) printf("-2\n"); else printf("%d\n", sdc.dis[n]);
} else
{
printf("-1\n");
}
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
init();
solve();
}
return 0;
}

------ 本文结束 ------