第十四届华中科技大学程序设计竞赛决赛 A-Beauty of Trees 【并查集】

题目描述 
It’s universally acknowledged that there’re innumerable trees in the campus of HUST.
One day the tree manager wants to play a game with you. There are N trees lining up in a straight road. The beauty of a set of trees is defined as the bitwise XOR sum of the heights of these trees. The game will last for M rounds, and each time he will tell you an interval [Li,Ri] and its beauty. However, he mixed some fake messages with the correct ones. Your task is to find the messages that cannot logically correspond to its former correct messages. Otherwise you’ll think the message is correct.
输入描述:
The first line contains two integer N and M(1≤N,M≤105), the number of trees and the rounds of game.
Then M lines followed, in each line are three integer L, R and k(1≤L≤R≤N,0≤k≤109), indicating that the beauty of [Li,Ri] is k.
输出描述:
If the i-th message is wrong, then print i in a single line.
If there is no mistake, print -1.
示例1
输入


3 4
1 3 6
1 2 5
3 3 10000
3 3 3
输出


3
说明


You can infer from the first two messages that the height of the third tree is 3.点击打开链接

#include<bits/stdc++.h>
using namespace std;
const int MAX = 2e5 + 7;
int pre[MAX];
int XOR[MAX];
int findx(int x)
{
    if(x != pre[x])
    {
        int tmp = pre[x];
        pre[x] = findx(pre[x]);
        XOR[x] = XOR[x] ^ XOR[tmp];
    }
    return pre[x];
}
int main()
{
    ios::sync_with_stdio(false);
    int n, m;
    cin >> n >> m;
    for(int i = 0; i <= n; i++)
    {
        XOR[i] = 0;
        pre[i] = i;
    }
    bool flag = 0;
    for(int i = 1, l, r, v; i <= m; i++)
    {
        cin >> l >> r >> v;
        l--;
        int L = findx(l);
        int R = findx(r);
        if(L == R)
        {
            if((XOR[l] ^ XOR[r]) != v)
            {
                flag = 1;
                cout << i << endl;
            }
        }
        else
        {
            pre[L] = R;
            XOR[L] = XOR[l] ^ XOR[r] ^ v;
        }
    }
    if(!flag)
        cout << "-1" << endl;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/head_hard/article/details/80215419