Background
Professor Hopper is researching the sexual behavior of a rare species of bugs. He assumes that they feature two different genders and that they only interact with bugs of the opposite gender. In his experiment, individual bugs and their interactions were easy to identify, because numbers were printed on their backs.
Problem
Given a list of bug interactions, decide whether the experiment supports his assumption of two genders with no homosexual bugs or if it contains some bug interactions that falsify it.
输入
The first line of the input contains the number of scenarios. Each scenario starts with one line giving the number of bugs (at least one, and up to 2000) and the number of interactions (up to 1000000) separated by a single space. In the following lines, each interaction is given in the form of two distinct bug numbers separated by a single space. Bugs are numbered consecutively starting from one.
输出
The output for every scenario is a line containing "Scenario #i:", where i is the number of the scenario starting at 1, followed by one line saying either "No suspicious bugs found!" if the experiment is consistent with his assumption about the bugs' sexual behavior, or "Suspicious bugs found!" if Professor Hopper's assumption is definitely wrong.
样例输入
2 3 3 1 2 2 3 1 3 4 2 1 2 3 4
样例输出
Scenario #1: Suspicious bugs found! Scenario #2: No suspicious bugs found!
大意就是在一群虫子里看有没有同性恋的虫子,通过观察“bug interactions” ,开始我还没反应过来bug interactions是什么23333
和食物链一个思想,向量,不过更简单了就是了,只有两种关系
不过数据集很大,需要scanf,c++用惯了...
visual studio里还需要声明下不要报错或者用scanf_s
#include<iostream>//需要scanf,
#include<stdio.h>
using namespace std;
int n_case;
int num, inter;
const int M = 2000;
int p[M + 1];//找上一个节点
int rela[M + 1];//和上一个节点的关系0是同性,1是异性。%2
int getroot(int a)
{
if (a == p[a])
{
return a;
}
int t = p[a];
p[a] = getroot(p[a]);
rela[a] = (rela[a] + rela[t]) % 2;//路径压缩,已经全部在根节点下
return p[a];
}
int main()
{
scanf_s("%d",&n_case);
int a, b;
bool flag;
for (int z = 1; z <= n_case; z++)
{
scanf_s("%d%d", &num, &inter);
for (int i = 1; i <= num; i++)
{
p[i] = i;
rela[i] = 0;
}//初始化
flag = 0;//开始没有找到同性恋
for (int i = 1; i <= inter; i++)
{
scanf_s("%d%d", &a, &b);
int r1 = getroot(a);
int r2 = getroot(b);//已经路径压缩
if (r1 != r2)//合并两棵树
{
p[r2] = r1;
rela[r2] = (rela[a] - rela[b] + 3) % 2;
}
else//在一棵树上
{
if (rela[a] == rela[b])
{
flag = true;//还有输入数据是不是不能break??
}
}
}
if (flag == true)
{
printf("Scenario #%d:\n", z);
printf("Suspicious bugs found!\n\n");
}
else if(flag==false)
{
printf("Scenario #%d:\n", z);
printf("No suspicious bugs found!\n\n");
}
}
return 0;
}