1 Star 0 Fork 1

saigon/Algorithms

forked from charlieshu/Algorithms 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
P1955 [NOI2015] │╠╨Є╫╘╢п╖╓╬Ў.cpp 1.84 KB
一键复制 编辑 原始数据 按行查看 历史
charlie 提交于 2024-01-09 00:01 . move from github to gitee
#include <iostream>
#include <set>
using namespace std;
struct num{
int father;
set<int> s;
};
num get(int x,num f[]){
if(f[x].father == x)
return f[x];
return f[x]=get(f[x].father,f);
}
void cac(){
int n;
cin>>n;
num f[n];
int rk[n];
for(int i=0;i<n;i++){
f[i].father = i;
rk[i] = 1;
}
bool out=true;
for(int i=0;i<n;i++){
int x,y,z;
cin>>x>>y>>z;
x--;
y--;
if(!out)
continue;
num fx,fy;
fx = get(x,f);
fy = get(y,f);
if(z == 1){
if(fx.father == fy.father)
continue;
if(fx.s.size() < fy.s.size()){
for(auto it=fx.s.begin();it!=fx.s.end();it++) {
num l;
l = get(*it,f);
fx.s.erase(*it);
if(l.father == fy.father){
out = false;
break;
}
fx.s.insert(l.father);
}
}
else{
for(auto it=fy.s.begin();it!=fy.s.end();it++) {
num l;
l = get(*it,f);
fy.s.erase(*it);
if(l.father == fy.father){
out = false;
break;
}
fy.s.insert(l.father);
}
}
if(!out)
continue;
if(rk[fx.father] == rk[fy.father]){
rk[fx.father]++;
f[fy.father].father = fx.father;
f[fx.father].s.insert(f[fy.father].s.begin(),f[fy.father].s.end());
}
else if(rk[fx.father] < rk[fy.father]){
f[fx.father].father = fy.father;
f[fy.father].s.insert(f[fx.father].s.begin(),f[fx.father].s.end());
}
else{
f[fy.father].father = fx.father;
f[fx.father].s.insert(f[fy.father].s.begin(),f[fy.father].s.end());
}
}
else{
if(fx.father == fy.father){
out = false;
}
f[fx.father].s.insert(fy.father);
f[fy.father].s.insert(fx.father);
}
}
if(out)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
return;
}
int main(){
int t;
cin>>t;
for(int k=0;k<t;k++){
cac();
}
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/saigonshu/algorithm.git
git@gitee.com:saigonshu/algorithm.git
saigonshu
algorithm
Algorithms
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385