zoukankan      html  css  js  c++  java
  • 51nod1515 明辨是非

    并查集合并好神的一道题。学到了map替代sort+unique的姿势。借鉴Monster__Yi这位神犇的题解!%%%%%

    #include<cstdio>
    #include<cstring>
    #include<cctype>
    #include<algorithm>
    #include<map>
    #include<set>
    using namespace std;
    #define rep(i,s,t) for(int i=s;i<=t;i++)
    #define dwn(i,s,t) for(int i=s;i>=t;i--)
    #define clr(x,c) memset(x,c,sizeof(x))
    int read(){
    	int x=0,f=1;char c=getchar();
    	while(!isdigit(c)){
    		if(c=='-') f=-1;c=getchar();
    	}
    	while(isdigit(c)) x=x*10+c-'0',c=getchar();
    	return x*f;
    } 
    const int nmax=2e5+5;
    int fa[nmax];
    set<int>s[nmax];
    map<int,int>m;
    int find(int x){
    	return fa[x]==x?x:fa[x]=find(fa[x]);
    }
    int main(){
    	int n=read(),u,v,d,cnt=0,ta,tb;
    	rep(i,1,n*2) fa[i]=i;
    	rep(i,1,n){
    		u=read(),v=read(),d=read();
    		if(m[u]) u=m[u];else u=m[u]=++cnt;
    		if(m[v]) v=m[v];else v=m[v]=++cnt;
    		ta=find(u),tb=find(v);
    		if(!d){
    			if(ta==tb) puts("NO");
    			else s[ta].insert(tb),s[tb].insert(ta),puts("YES");
    		}else{
    			if(ta==tb) puts("YES");
    			else if(s[ta].count(tb)) puts("NO");
    			else{
    				puts("YES");
    				if(s[ta].size()>s[tb].size()) swap(ta,tb);
    				for(set<int>::iterator it=s[ta].begin();it!=s[ta].end();it++)
    				  s[*it].erase(ta),s[*it].insert(tb),s[tb].insert(*it);
    				fa[ta]=tb;
    			}
    		}
    	}
    	return 0;
    }
    

      

    题目来源: 原创
    基准时间限制:1 秒 空间限制:131072 KB 分值: 160 难度:6级算法题
     收藏
     关注

    给n组操作,每组操作形式为x y p。

    当p为1时,如果第x变量和第y个变量可以相等,则输出YES,并限制他们相等;否则输出NO,并忽略此次操作。

    当p为0时,如果第x变量和第y个变量可以不相等,则输出YES,并限制他们不相等 ;否则输出NO,并忽略此次操作。

    Input
    输入一个数n表示操作的次数(n<=1*10^5)
    接下来n行每行三个数x,y,p(x,y<=1*10^8,p=0 or 1)
    Output
    对于n行操作,分别输出n行YES或者NO
    Input示例
    3
    1 2 1
    1 3 1
    2 3 0
    Output示例
    YES
    YES
    NO
  • 相关阅读:
    linux下git以及github的连接与使用
    在windows上如何安装python web引擎jinja2
    JS请求服务器并使页面跳转(转)
    Spring MVC中Session的正确用法<转>
    Eclipse上安装GIT插件EGit及使用
    深入理解JavaScript事件循环机制
    React Hooks useContext 进行父子组件传值
    Remove all your local git branches but keep master
    常见的web前端性能优化
    js知识梳理2:对象属性的操作
  • 原文地址:https://www.cnblogs.com/fighting-to-the-end/p/5861207.html
Copyright © 2011-2022 走看看