第十四届华中科技大学程序设计竞赛决赛-A:Beauty of Trees(带权并查集)

链接:https://www.nowcoder.com/acm/contest/119/A
来源:牛客网

时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

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 [L i,R i] 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.

思路:带权并查集。r[i]表示[i,p[i]]之间所有数的异或值。在现场的时候想出是这么做,却没有实现出来,悲伤。

#include<bits/stdc++.h>
using namespace std;
const int MAX=1e5+10;
const double PI=acos(-1.0);
typedef long long ll;
int p[MAX],r[MAX];
int f(int x)
{
    if(p[x]==x)return x;
    int nex=p[x];
    p[x]=f(p[x]);
    r[x]^=r[nex];
    return p[x];
}
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=0;i<=n;i++)p[i]=i,r[i]=0;
    int tag=0;
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        scanf("%d%d%d",&x,&y,&z);
        x--;
        int fx=f(x),fy=f(y);
        if(fx==fy)
        {
            if((r[x]^r[y])!=z)
            {
                printf("%d\n",i);
                tag=1;
            }
        }
        else
        {
            p[fy]=fx;
            r[fy]=r[y]^z^r[x];
        }
    }
    if(tag==0)puts("-1");
    return 0;
}



猜你喜欢

转载自blog.csdn.net/mitsuha_/article/details/80233175