zoukankan      html  css  js  c++  java
  • 程序自动分析 并查集+离散化

    程序自动分析

    题意:

    给定n个约束条件,有相等和不相等两种,判断n个约束条件是否矛盾;

    思路:

    并查集维护的是具有传递性的关系,相等具有传递性,可以先用并查集维护相等的约束条件,再判断与不相等的约束条件是否矛盾;

    细节:

    注意离散化,另外由于多组数据,注意初始化!!!

    代码

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm> 
    #define LL long long
    using namespace std;
    const int N=1e6+7;
    struct node{
    	int x,y; 
    	bool z;
    	friend bool operator <(const node &x,const node &y){
    		return  x.z>y.z;
    	}
    }a[N];	
    int T,n,cnt;
    int b[N<<1];
    int fa[N<<1];
    int find(int x){
    	if(fa[x]==x) return x;
    	return fa[x]=find(fa[x]);
    }
    int main(){
    	scanf("%d",&T);
    	while(T--){
    		scanf("%d",&n);
    		cnt=0;
    		for(int i=1;i<=n;i++){
    			scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].z);
    			b[++cnt]=a[i].x;
    			b[++cnt]=a[i].y;
    		}
    		sort(b+1,b+cnt+1);
    		sort(a+1,a+n+1);
    		int m=unique(b+1,b+cnt+1)-b-1;
    		for(int i=1;i<=n;i++){
    			a[i].x=lower_bound(b+1,b+m+1,a[i].x)-b;
    			a[i].y=lower_bound(b+1,b+m+1,a[i].y)-b;
    		}
    		for(int i=1;i<=m;i++) fa[i]=i;
    //		for(int i=1;i<=m;i++) cout<<b[i]<<"
    ";
    		int flag=0;
    		for(int i=1;i<=n;i++){
    //			cout<<a[i].x<<" "<<a[i].y<<"
    ";
    			if(a[i].z==1){
    				int tx=find(a[i].x),ty=find(a[i].y);
    				if(tx!=ty) fa[tx]=ty;
    			}
    			if(a[i].z==0){
    				int tx=find(a[i].x),ty=find(a[i].y);
    				if(tx==ty){
    					flag=1;
    					break;
    				}
    			}
    		}
    		if(flag==1) cout<<"NO";
    		else cout<<"YES";
    		cout<<"
    ";
    	}
    }
    /*
    2 2
    1000000000 999999999 1
    1000000000 999999998 0
    */
    
  • 相关阅读:
    UVA11825 Hackers' Crackdown
    UVA 11346 Probability
    Codeforces 12 D Ball
    bzoj 4766: 文艺计算姬
    Codeforces 757 F Team Rocket Rises Again
    [HAOI2011] problem C
    Atcoder 3857 Median Sum
    bzoj4399 魔法少女LJJ
    bzoj2638 黑白染色
    bzoj4197 [Noi2015]寿司晚宴
  • 原文地址:https://www.cnblogs.com/Aswert/p/13563312.html
Copyright © 2011-2022 走看看