# 样例1

## 样例输入1

9 9
1 2 3
2 3 5
2 7 1
4 5 4
5 6 1
5 9 1
6 7 1
7 8 3
9 8 4


## 样例输出1

2
5
10
0
4
5
6
9
5


1s

N,P<=500

# 来源

Balkan OI 1998

1、rootx比rooty高

2、rooty比rootx高

if(d[x]-d[y]+z>=0) {
fa[rooty]=rootx;
d[rooty]=d[x]-d[y]+z;
}
if(d[x]-d[y]+z<0) {
fa[rootx]=rooty;
d[rootx]=-(d[x]-d[y]+z);
}

int find(int x) {
if(fa[x]==0) return x;
int y=find(fa[x]);
d[x]+=d[fa[x]];
return fa[x]=y;
}

#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;

int n,m;
int d[510]= {0},fa[510]= {0};

int find(int x) {
if(fa[x]==0) return x;
int y=find(fa[x]);
d[x]+=d[fa[x]];
return fa[x]=y;
}

int main() {

scanf("%d%d",&n,&m);
for(int i=1; i<=m; i++) {
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
int rootx=find(x),rooty=find(y);
if(rootx!=rooty) {
if(d[x]-d[y]+z>=0) {	//要分类讨论
fa[rooty]=rootx;
d[rooty]=d[x]-d[y]+z;
}
if(d[x]-d[y]+z<0) {
fa[rootx]=rooty;
d[rootx]=-(d[x]-d[y]+z);
}
} else {
if(d[y]!=d[x]+z) {
printf("-1");
return 0;
}
}
}

for(int i=1; i<=n; i++) {
find(i);
printf("%d\n",d[i]);
}

return 0;
}

02-14 29

06-19 329
07-10 32
12-02 167
05-13 1464
10-19 140
02-22 246
11-03 1598