# 【Atcoder abc087 D】People on a Line，BFS，图遍历

#### problem

D - People on a Line / Time Limit: 2 sec / Memory Limit: 256 MB Score : 400 points Problem Statement There are N people standing on the x -axis. Let the coordinate of Person i be x i . For every i , x i is an integer between 0 and 10 9 (inclusive). It is possible that more than one person is standing at the same coordinate. You will given M pieces of information regarding the positions of these people. The i -th piece of information has the form ( L i , R i , D i ) . This means that Person R i is to the right of Person L i by D i units of distance, that is, x R i − x L i = D i holds. It turns out that some of these M pieces of information may be incorrect. Determine if there exists a set of values ( x 1 , x 2 , . . . , x N ) that is consistent with the given pieces of information. Constraints 1 ≤ N ≤ 100 000 0 ≤ M ≤ 200 000 1 ≤ L i , R i ≤ N ( 1 ≤ i ≤ M ) 0 ≤ D i ≤ 10 000 ( 1 ≤ i ≤ M ) L i ≠ R i ( 1 ≤ i ≤ M ) If i ≠ j , then ( L i , R i ) ≠ ( L j , R j ) and ( L i , R i ) ≠ ( R j , L j ) . D i are integers. Input Input is given from Standard Input in the following format: N M L 1 R 1 D 1 L 2 R 2 D 2 : L M R M D M Output If there exists a set of values ( x 1 , x 2 , . . . , x N ) that is consistent with all given pieces of information, print Yes; if it does not exist, print No. Sample Input 1 Copy 3 3 1 2 1 2 3 1 1 3 2 Sample Output 1 Copy Yes Some possible sets of values ( x 1 , x 2 , x 3 ) are ( 0 , 1 , 2 ) and ( 101 , 102 , 103 ) . Sample Input 2 Copy 3 3 1 2 1 2 3 1 1 3 5 Sample Output 2 Copy No If the first two pieces of information are correct, x 3 − x 1 = 2 holds, which is contradictory to the last piece of information. Sample Input 3 Copy 4 3 2 1 1 2 3 5 3 4 2 Sample Output 3 Copy Yes Sample Input 4 Copy 10 3 8 7 100 7 9 100 9 8 100 Sample Output 4 Copy No Sample Input 5 Copy 100 0 Sample Output 5 Copy Yes

#### solution

/*
+ n个人，每个人的位置为xi。m条信息，ri在li右边d的位置。
+ 求判断是否存在一组信息子集不冲突。
+ 以{l,r,d}为边建立有向图，跑一遍最短路，如果遇到冲突就No
*/
#include<bits/stdc++.h>
using namespace std;
struct node{int u, dist;};
int main(){
int n, m;  cin>>n>>m;
vector<vector<node>>G(n);
for(int i = 0; i < m; i++){
int l, r, d;  cin>>l>>r>>d;
l--; r--;
G[l].push_back(node({r, d}));
G[r].push_back(node({l, -d}));
}
vector<int>dist(n,-2e9);
for(int i = 0; i < n; i++){
if(dist[i]!=-2e9)continue;
dist[i] = 0;
queue<int>q;
q.push(i);
while(q.size()){
int t = q.front();  q.pop();
for(auto to:G[t]){
if(dist[to.u] == -2e9){
dist[to.u] = dist[t] + to.dist;
q.push(to.u);
}else{
if(dist[to.u] == dist[t] + to.dist)continue;
else {
cout<<"No\n"; return 0;
}
}
}
}
}
cout<<"Yes\n";
return 0;
}


01-13 1561

08-13 159
07-31 4660
09-11 333
07-22 272
10-20 6060
03-12 9150
08-19 213
05-14 1万+
05-18 1376
08-04 929
08-11 259
01-13 175
02-13 6709