程序自动分析(并查集 + 离散化)

本文介绍了在程序自动分析中如何利用并查集解决约束满足问题。通过并查集来判断变量之间的相等或不等约束是否能够同时满足,通过离散化处理大范围的数据。示例展示了具体的输入输出格式,并提供了C++代码实现。
摘要由CSDN通过智能技术生成

Description

在实现程序自动分析的过程中,常常需要判定一些约束条件是否能被同时满足。
考虑一个约束满足问题的简化版本:假设x1,x2,x3,…代表程序中出现的变量,给定n个形如xi=xj或xi≠xj的变量相等/不等的约束条件,请判定是否可以分别为每一个变量赋予恰当的值,使得上述所有约束条件同时被满足。例如,一个问题中的约束条件为:x1=x2,x2=x3,x3=x4,x1≠x4,这些约束条件显然是不可能同时被满足的,因此这个问题应判定为不可被满足。
现在给出一些约束满足问题,请分别对它们进行判定。 Input
输入文件的第1行包含1个正整数t,表示需要判定的问题个数。注意这些问题之间是相互独立的。 对于每个问题,包含若干行:
第1行包含1个正整数n,表示该问题中需要被满足的约束条件个数。
接下来n行,每行包括3个整数i,j,e,描述1个相等/不等的约束条件,相邻整数之间用单个空格隔开。若e=1,则该约束条件为xi=xj;若e=0,则该约束条件为xi≠xj。
Output 输出文件包括t行。
输出文件的第k行输出一个字符串“YES”或者“NO”(不包含引号,字母全部大写),“YES”表示输入中的第k个问题判定为可以被满足,“NO”表示不可被满足。
Sample Input 2 2 1 2 1 1 2 0 2 1 2 1 2 1 1 Sample Output NO YES
HINT 在第一个问题中,约束条件为:x1=x2,x1≠x2。这两个约束条件互相矛盾,因此不可被同时满足。
在第二个问题中,约束条件为:x1=x2,x2=x1。这两个约束条件是等价的,可以被同时满足。 1≤n≤1000000
1≤i,j≤1000000000

题解

这道题显然是一道并查集的题。 若把每个变量看成一个节点那么判断相等的条件即为这两个点在无向图中连通,那么就可以用到并查集。
对于本题来说,数据范围到了1e91e9,那么我们就需要用到离散化。 离散化可以先排序,在判重,最后lower−bound(stl函数)

第一种做法 并查集 + 离散化

/**
/*@author Victor
/*language C++
*/
//#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
//#include<map>
#include<set>
//#define DEBUG
#define RI register int
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=100000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pil pair<int , ll>
#define pli pair<ll,int>
#define pdl pair<double,ll>
#define pld pair<ll,double>
#define pdd pair<double,double>
#define iput(n) scanf("%d",&n)
#define iiput(a,n) scanf("%d%d",&a,&n)
#define iiiput(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define dput(n) scanf("%lf",&n)
#define llput(n) scanf("%lld",&n)
#define cput(n) scanf("%s",n)
#define puti(n) printf("%d\n",n)
#define putll(n) printf("%lld\n",n)
#define putd(n) printf("%lfd\n",n)
#define _cls(n) memset(n,0,sizeof(n))
#define __cls(n) memset(n,INF,sizeof(n))
//priority_queue <int,vector<int>,greater<int> > Q;//优先队列递增
//priority_queue<int>Q;//递减
//map<ll,ll>mp;
//set<ll>st;
//stack<>st;
//queue<>Q;
#define F first
#define S second
#define pb push_back
#define PB push_back
#define MP make_pair
#
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值