电影节
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
某届电影节评选电影,共有两部电影进入最后评选环节,有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 2 1 2 2 3 1 3 5 2 1 2 3 4 1 4 5 2 1 2 3 4 2 5
示例输出
same not sure not sure
运用并查集思想。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int pre[100100];
int find(int x)
{
int r=x;
while(pre[r]!=r)//<span style="font-size:12px;"><strong>注意</strong></span><strong>:</strong>这是个循环,并且很多pre[r]不再等于r了,所以可能会循环很多次,所以返回值r也会变很多次。
{
r=pre[r];
}
return r;
}
void join(int x,int y)
{
int fx=find(x),fy=find(y);
if(fx!=fy)
{
pre[fx]=fy;
}
}
void join2(int x,int y)
{
int fx=find(x),fy=find(y);
if(fx==fy)
{
cout<<"same"<<endl;
}
else
{
cout<<"not sure"<<endl;
}
}
int main()
{
int n,m,a,b,c,d;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=1; i<=n; i++)
{
pre[i]=i;
}
for(int i=0; i<m; i++)
{
cin>>a>>b;
join(a,b);
}
cin>>c>>d;
join2(c,d);
}
return 0;
}