您的位置:首页 > 其它

并查集初学(4)向量思维 POJ1182(食物链)&& POJ1703

2016-05-08 09:37 441 查看
分析:这两个题,便算是初学者中的大成题了,学会了这两个题,几乎并查集算是入门了,可以秒掉不少题了

POJ1182

一般博客都只是给了一个公式,不给推导过程,对于这个公式,有很多理解办法,但我认为应该是用向量思维来理解最好,简单明了

此大神写的详解非常完美(可以借鉴):http://blog.csdn.net/c0de4fun/article/details/7318642/

这位大牛也非常牛:http://blog.csdn.net/freezhanacmore/article/details/8767413

我只能写出代码,还不能很完美的解释此问题,仰视大牛:::::

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 50010

struct node
{
int pre;
int relation;
};
node p
;

int find(int x) //查找根结点
{
int temp;
if(x == p[x].pre)
return x;
temp = p[x].pre; //路径压缩
p[x].pre = find(temp);
p[x].relation = (p[x].relation + p[temp].relation) % 3; //关系域更新
return p[x].pre; //根结点
}

int main()
{
int n, k;
int ope, a, b;
int root1, root2;
int sum = 0; //假话数量
scanf("%d%d", &n, &k);
for(int i = 1; i <= n; ++i) //初始化
{
p[i].pre = i;
p[i].relation = 0;
}
for(int i = 1; i <= k; ++i)
{
scanf("%d%d%d", &ope, &a, &b);
if(a > n || b > n) //条件2
{
sum++;
continue;
}
if(ope == 2 && a == b) //条件3
{
sum++;
continue;
}
root1 = find(a);
root2 = find(b);
if(root1 != root2) // 合并
{
p[root2].pre = root1;
p[root2].relation = (3 + (ope - 1) +p[a].relation - p[b].relation) % 3;
}
else
{
if(ope == 1 && p[a].relation != p[b].relation)
{
sum++;
continue;
}
if(ope == 2 && ((3 - p[a].relation + p[b].relation) % 3 != ope - 1))
{
sum++;
continue;}
}
}
printf("%d\n", sum);
return 0;
}


2、第二个类似第一个,将食物链的三类改成了两类,一边路径压缩,一边关系域更新便可

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int maxn=100005;

int p[maxn],ans[maxn];
int n;

void init()
{
for (int i=1;i<=n;i++)
{
p[i]=i;
ans[i]=0;
}
}

int Find(int x)
{
if (x == p[x]) return x; //注意tp的使用
int tp=Find(p[x]);
ans[x]=ans[x]^ans[p[x]];
return p[x]=tp;
}

void Union(int x,int y)
{
int fx=Find(x);
int fy=Find(y);
p[fx]=fy;
ans[fx]=~(ans[y]^ans[x]);
}

int main()
{
int t,m;
scanf("%d",&t);
while (t--)
{
scanf("%d%d",&n,&m);
init();
char relation[2];
int a,b;
for (int i=0;i<m;i++)
{
scanf("%s%d%d",relation,&a,&b);
if (relation[0] == 'D') Union(a,b);
else
{
if (n == 2)
{
printf("In different gangs.\n");
}
else if (Find(a) == Find(b))
{
if (ans[a] == ans[b]) printf("In the same gang.\n");
else printf("In different gangs.\n");
}
else printf("Not sure yet.\n");
}

}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: