并查集 POJ 1703

来源:互联网 发布:ubuntu如何安装输入法 编辑:程序博客网 时间:2024/05/17 08:25

题意:
有两个帮派,给你A信息,让你输出这两人是不是一个帮派的;给你D信息,表示这俩人不是一个帮派的,给你A信息后,每次输出你的回答
题解:
又是简单的并查集,但是很坑的就是cin会超时,然后并不知道是不是cout和scanf这种出现了不可预知到错误,然后就是init少了一个,唉,这题还是应该注意编号啊,以后就直接按编号来,别没事都从0开始

#include<iostream>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<queue>#define pr(x) cout<<#x<<" "<<x;#define pl(x) cout<<#x<<" "<<x<<endl;#include<math.h>#include<algorithm>using namespace std;#define MAX_LEN 200010int fa[MAX_LEN];int ranks[MAX_LEN];void init(int n){    for(int i = 0;i<n;i++){        fa[i] = i;        ranks[i] = 0;    }}int find(int i){    if(i == fa[i]){return i;}    else{        return fa[i] = find(fa[i]);        //return fa[i];    }}void uint(int a, int b){    int x = find(a);    int y = find(b);    if(x == y){return ;}    else{        if(ranks[x] > ranks[y]){            fa[y] = x;        }        else{            fa[x] = y;            if(ranks[x]==ranks[y]){                ranks[y]++;            }        }    }}bool same(int i,int j){    return find(i)==find(j);}int main(){    int t;    scanf("%d",&t);    while(t--){        int n,m;        scanf("%d%d",&n,&m);        init(2*n+2);        //getchar();        char ch;int a,b;        while(m--){          getchar();            scanf("%c%d%d",&ch,&a,&b);            //getchar();            if(ch =='A'){                if(same(a,b)){                    puts("In the same gang.");                   // cout << "In the same gang." << endl;//continue;                }                 else if(same(a,b+n)){                     puts("In different gangs.");                   // cout << "In different gangs." << endl;                    //continue;                }                else{                    puts("Not sure yet.");                  // cout<<"Not sure yet."<<endl;                  // continue;                }            }            else {                uint(a,b+n);                uint(a+n,b);            }        }    }    return 0;}
0 0
原创粉丝点击