AtCoder Regular Contest 090 D - People on a Line

Problem Statement
There are N people standing on the x-axis. Let the coordinate of Person i be xi. For every i, xi is an integer between 0 and 109 (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 (Li,Ri,Di). This means that Person Ri is to the right of Person Li by Di units of distance, that is, xRi−xLi=Di holds.

It turns out that some of these M pieces of information may be incorrect. Determine if there exists a set of values (x1,x2,…,xN) that is consistent with the given pieces of information.

Constraints
1≤N≤100 000
0≤M≤200 000
1≤Li,Ri≤N (1≤i≤M)
0≤Di≤10 000 (1≤i≤M)
Li≠Ri (1≤i≤M)
If i≠j, then (Li,Ri)≠(Lj,Rj) and (Li,Ri)≠(Rj,Lj).
Di are integers.
Input
Input is given from Standard Input in the following format:

N M
L1 R1 D1
L2 R2 D2
:
LM RM DM
Output
If there exists a set of values (x1,x2,…,xN) 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 (x1,x2,x3) 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, x3−x1=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
题意:有n个人,m个关系 (Li,Ri,D) 表示 第Li个人在第Ri个人的的左边距离为D,问存不存在这样的数对使得这m个关系成立。做法并查集: d[x] 表示 x 离x的父亲的距离 在合并的时候判断该关系是否成立就行。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 2e5 + 100;
int f[maxn];
int d[maxn];
int ff(int x){
    if (f[x] == x) return x;
    int a = f[x];
    int b = ff(f[x]);
    d[x] += d[a]; 
    f[x] = b;
    return b;
}
int unit(int x,int y,int z){
    int fx = ff(x);
    int fy = ff(y);
    if (fx == fy){
        return (d[y] - d[x]) == z;
    }
    f[fy] = fx;
    d[fy] = d[x] + z -d[y];
    return 1;
}
int main(){
    int n,m;
    scanf("%d%d",&n,&m);
    for (int i = 1; i <= n; i++) f[i] = i;
    int flag = 0;
    for (int i = 0; i < m; i++){
        int x,y,d;
        scanf("%d%d%d",&x,&y,&d);
        if (!unit(x,y,d))
        {
            flag = 1;
        }
    }
    if (flag) printf("No\n");
    else printf("Yes\n");
}

你可能感兴趣的:(并查集)