题目:
题目链接:https://www.luogu.org/problem/P5651?contestId=23456
给定
n
n
n个点
m
m
m条边的无向简单联通图
G
G
G,边有边权。保证没有重边和自环。
定义一条简单路径的权值为路径上所有边边权的异或和。
保证 G G G中不存在简单环使得边权异或和不为0。
Q Q Q次询问 x x x到 y y y的最短简单路径。
思路:
题目保证了每一个简单环的异或和均为0。也就是说对于环上的任意两点
(
x
,
y
)
(x,y)
(x,y),从
x
→
y
x\to y
x→y的两条路径的权值相等。
所以对于每一个环,我们只要保留其中的一条路径即可。也就是说,我们可以把这张图变成一棵树。
然后图上的两点的距离就唯一了。
所以我们从节点1开始
d
f
s
dfs
dfs,求出每一个点到1的路径异或和。那么路径
x
→
y
x\to y
x→y的答案就是
x
→
1
x
o
r
y
→
1
x\to 1\ xor\ y\to 1
x→1 xor y→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\n",dis[x]^dis[y]);
}
return 0;
}