【洛谷P5651】基础最短路练习题【dfs】【并查集】

题目:

题目链接:https://www.luogu.org/problem/P5651?contestId=23456
给定nn个点mm条边的无向简单联通图GG,边有边权。保证没有重边和自环。

定义一条简单路径的权值为路径上所有边边权的异或和。

保证GG中不存在简单环使得边权异或和不为0。

QQ次询问xxyy的最短简单路径。


思路:

题目保证了每一个简单环的异或和均为0。也就是说对于环上的任意两点(x,y)(x,y),从xyx o y的两条路径的权值相等。
所以对于每一个环,我们只要保留其中的一条路径即可。也就是说,我们可以把这张图变成一棵树。
然后图上的两点的距离就唯一了。
所以我们从节点1开始dfsdfs,求出每一个点到1的路径异或和。那么路径xyx o y的答案就是x1 xor y1x o 1 xor y o 1


代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N=100010;
int n,m,Q,tot,head[N],dis[N],father[N];

struct edge
{
	int next,to,dis;
}e[N*2];

void add(int from,int to,int dis)
{
	e[++tot].to=to;
	e[tot].dis=dis;
	e[tot].next=head[from];
	head[from]=tot;
}

int find(int x)
{
	return x==father[x]?x:father[x]=find(father[x]);
}

void dfs(int x,int fa)
{
	for (int i=head[x];~i;i=e[i].next)
	{
		int v=e[i].to;
		if (v!=fa)
		{
			dis[v]=dis[x]^e[i].dis;
			dfs(v,x);
		}
	}
}

int main()
{
	memset(head,-1,sizeof(head));
	scanf("%d%d%d",&n,&m,&Q);
	for (int i=1;i<=n;i++)
		father[i]=i;
	for (int i=1,x,y,z;i<=m;i++)
	{
		scanf("%d%d%d",&x,&y,&z);
		if (find(x)!=find(y))
		{
			father[find(x)]=find(y);
			add(x,y,z); add(y,x,z);
		}
	}
	dfs(1,0);
	while (Q--)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		printf("%d
",dis[x]^dis[y]);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/hello-tomorrow/p/11997982.html