P1955 [NOI2015] 程序自动分析
vector 离散化常数大
离散化之后,数的下标是从
0
0
0 开的,当然也可以从
1
1
1 开始,要留意这个点
这题不能用种类并查集,因为种类不止两三个,每个数都可能是一种
code:
#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define eps 1e-6
using namespace std;
const int maxn = 2e6 + 9;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll n, m;
int f[maxn];
int find(int x){
return f[x] == x ? x : f[x] = find(f[x]);
}
void merge(int x, int y){
x = find(x); y = find(y);
if(x != y) f[x] = y;
}
struct node{
int x, y, z;
}a[maxn];
void work()
{
cin >> n;
vector <int> v;
for(int i = 1; i <= n; ++i){
cin >> a[i].x >> a[i].y >> a[i].z;
v.push_back(a[i].x);
v.push_back(a[i].y);
}
sort(all(v));// 与 unique 搭配
v.erase(unique(v.begin(), v.end()), v.end());// vector 离散化
// unique 是返回的是尾地址,与sort一样,区间左闭右开
// 尾地址一般是最后一个合法元素的下一位
// 数组大小是尾地址减去首地址
for(int i = 0; i <= v.size(); ++i) f[i] = i;// 注意从 0 开始
bool flag = 0;
for(int i = 1, x, y; i <= n; ++i){
x = lower_bound(v.begin(), v.end(), a[i].x) - v.begin();
y = lower_bound(v.begin(), v.end(), a[i].y) - v.begin();
if(a[i].z == 1) merge(x, y);
}
for(int i = 1, x, y; i <= n; ++i){
x = lower_bound(v.begin(), v.end(), a[i].x) - v.begin();
y = lower_bound(v.begin(), v.end(), a[i].y) - v.begin();
if(a[i].z == 0 && find(x) == find(y)) flag = 1;
}
cout << (flag ? "NO" : "YES") << endl;
}
int main()
{
ios::sync_with_stdio(0);
int TT;cin>>TT;while(TT--)
work();
return 0;
}