杭电1829——并差集+性别判断
写在前面:
这个题让我们判断有没有同性恋(好变态哦),需要用并差集来做,不过还需要判断性别。虽然是用并差集但是跟平常的还是有点区别的(注意meg和fin函数的变化)。
解题思路:
判断两个昆虫是否相连
1、如果没有,用meg函数连起来。
2、如果已经相连,就判断两个昆虫是否同性,怎么判断呢,其实我们可以通过节点到最上面的节点距离来判断(用len数组存),如果两个节点的len的差值是奇数,说明两个节点异性,反之就是同性。
写在最后:
这题没坑,这题没坑,这题没坑!!!
你想多了,这种题怎么没坑呢。明明代码已经码出来了,就是提示输出错误,然后发现每个样例之间需要空一行。哈哈,我终于找到了,根据我多年(可能是多月)acm的经验,既然样例之间要空行,那么最后一个样例肯定没有空行。结果一提交,woc,心中一万个草泥马路过,为什么还是输出错误,这个有毒吧,不做了。手动狗头。。。
其实最后一个样例也是有空行的,呃,怎么说呢,上图:
看吧,人家是有空行的。
唉,菜是原罪,我是滚回去重新学吧。
ac代码:
# include <iostream>
# include <algorithm>
# include <cstdio>
# include <cstdlib>
# include <string>
# include <cstring>
# include <vector>
using namespace std;
const int maxn = 2005;
int id[maxn];
int len[maxn];//len[i]记录i到最上面的节点的距离
int fin(int a) {//注意这个fin函数,没有用路径压缩
int x = a;
int l = 0;
while (x != id[x]) {
x = id[x];
l++;//在往上面遍历的时候,记录距离
}
len[a] = l;
return x;
}
void meg(int x, int y) {//注意这里的meg函数是直接将x和y连起来
if (id[y] == y) {//如果y没被访问过
id[y] = x;
}
else {//如果x没被访问过
id[x] = y;
}
}
bool same(int x, int y) {
return fin(x) == fin(y);
}
int main() {
ios::sync_with_stdio(false);
//freopen("mainin.txt", "r", stdin);
int T;
cin >> T;
for (int ti = 1; ti <= T; ti++) {
for (int i = 0; i < maxn; i++) {
id[i] = i;
}
memset(len, 0, sizeof(len));
//注意初始化。
int m, n;
cin >> m >> n;
string ans = "No suspicious bugs found!";
while (n--) {
int a, b;
cin >> a >> b;
if (!same(a, b)) {
meg(a, b);
}
else {
if (abs(len[a] - len[b]) % 2 == 0) {//如果a和b的距离差为偶数,说明a和b同性,ans记为"no"
ans = "Suspicious bugs found!";
}
}
}
cout << "Scenario #" << ti << ":" << endl<< ans << endl<<endl;
}
return 0;
}