2020-10-10 离散化+例题

笔记

在这里插入图片描述

例题

题目

P1955 [NOI2015]程序自动分析
链接
(https://www.luogu.com.cn/problem/P1955)

分析

并查集+离散化
并查集find迭代70分,太坑了,得递归。

代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>

using namespace std;
const int maxn = 1e6 + 10;
int father[maxn],lsh[maxn*3];
struct node
{
    long long a,b;
    int e;
}arr[maxn];

bool cmp(node a,node b)
{
    return a.e > b.e;
}

int findf(int x)
{
    if(x==father[x])
        return x;
    else return father[x]=findf(father[x]);
}

int main()
{
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        memset(lsh,0,sizeof(lsh));
        memset(arr,0,sizeof(arr));
        memset(father,0,sizeof(father));
        scanf("%d",&n);
        int k = 0;
        for(int i = 1;i <= n;i++)
        {
            scanf("%lld%lld%d",&arr[i].a,&arr[i].b,&arr[i].e);
            lsh[k++] = arr[i].a;
            lsh[k++] = arr[i].b;
        }
        sort(lsh,lsh+k);
        int num = unique(lsh,lsh+k)-lsh;
        for(int i = 1;i <= n;i++)
        {
            arr[i].a = lower_bound(lsh,lsh+num,arr[i].a)-lsh;
            arr[i].b = lower_bound(lsh,lsh+num,arr[i].b)-lsh;
        }
        sort(arr+1,arr+n+1,cmp);
        for(int i = 1;i <= num;i++)
            father[i] = i;
        int flag = 1;
        for(int i =1;i <= n;i++)
        {
            int fx = findf(arr[i].a);
            int fy = findf(arr[i].b);
            if(arr[i].e)
            {
                father[fx]=fy;
            }
            else if(fx == fy)
            {
                flag = 0;
                break;
            }
        }
        if(flag)
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值