2797 电影节 并查集

来源:互联网 发布:设计展板的软件 编辑:程序博客网 时间:2024/06/13 10:23

题目描述

某届电影节评选电影,共有两部电影进入最后评选环节,有n名观众,每个人有一次投票的机会,每个人都按照规则投给其中一部电影。为了了解情况,记者随机询问了一些人,一共询问了m次,特别神奇的是,记者每次都询问两个人,而且这两个人都把票投给了同一部电影,观众编号为1~n。
  

输入

   
多组输入,每组第一行是两个整数n,m (2 <= n <=100000,0 <= m < n/2),接下来m行数据,表示m次询问,每行数据有两个整数a,b代表观众的编号(1 <= a,b <= n),观众a和观众b投票给了同一部电影,接下来一行是两个整数c,d(1 <= c,d <= n)。
  

输出

   
对于每一组输入,输出一行,如果观众c和观众d投票给同一部电影,输出”same”,如果不能确定,输出”not sure”。
  

示例输入

   
5 21 22 31 35 21 23 41 45 21 23 42 5
  

示例输出

   
samenot surenot sure
        

提示

   
 
          

来源

   
xj
 
 
#include <stdio.h>#include <stdlib.h>#include <string.h>int q[100001];int find(int x){    int r=x;    while(r!=q[r])        r=q[r];    return r;}int add (int a,int b){    int fa,fb;    fa = find (a);    fb = find(b);    if (fa != fb)        q[fa] = fb;}int pd (int a,int b){    int fa,fb;    fa = find (a);    fb = find (b);    if (fa != fb)        printf("not sure\n");    else        printf("same\n");}int main(){    int i;    int n,m;    while (~scanf ("%d%d",&n,&m))    {        int a,b;        memset(q,0,sizeof (q));        for (i = 0; i < 100001; i++)            q[i] = i;        for (i = 1; i <= m; i++)        {            scanf ("%d%d",&a,&b);            add(a,b);        }        scanf ("%d%d",&a,&b);        pd (a,b);    }    return 0;}

把“个体”的比较化为“类”的比较,这里通过上溯找树的父节点,进行添加,比较。
0 0