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

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

题目描述

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.

题解:
枚举c[i]二进制上的每一位,若在某一位上为1,则前a[i]-1和前b[i]个数
在该位上为1的总数同为奇数或偶数。否则一奇一偶。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+7;
int par[maxn],a[maxn],b[maxn],c[maxn];
bool is[maxn];
void init()
{
    for(int i=0;i<maxn;i++)
        par[i]=i;
}
int find(int x)
{
    if(x==par[x])return x;
    return par[x]=find(par[x]);
}
void unite(int x,int y)
{
    x=find(x);y=find(y);
    if(x!=y)
        par[x]=y;
}
int main()
{
    int n,m;
    memset(is,1,sizeof(is));
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
        scanf("%d%d%d",&a[i],&b[i],&c[i]);
    int T=30;
    bool bb=0;
    while(T--)
    {
        init();
        for(int i=1;i<=m;i++)
        {
            if(!is[i])continue;
            int x=a[i],y=b[i];
            if(c[i]%2)
            {
                if(find(x-1)==find(y))is[i]=0,bb=1;
                else unite(x-1,y+n+1),unite(x+n,y);
            }
            else
            {
                if(find(x-1)==find(y+n+1))is[i]=0,bb=1;
                else unite(x-1,y),unite(x+n,y+n+1);
            }
            c[i]/=2;
        }
    }
    if(!bb)printf("-1\n");
    else
    {
        for(int i=1;i<=m;i++)
            if(!is[i])
            printf("%d\n",i);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/albertluf/article/details/80257731