「 Luogu P2420 」 让我们异或吧
生活随笔
收集整理的這篇文章主要介紹了
「 Luogu P2420 」 让我们异或吧
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
# 解題思路
兩點之間的路徑的話一定經過它們兩個 LCA,這一點已經是顯而易見的,那么再來看看異或的性質。
$$a\ xor\ b\ xor\ b = a\\ a\ xor\ a=0\\ a\ xor\ 0 = a\\ a\ xor\ b = b\ xor\ a\\ a\ xor\ b\ xor\ c = a\ xor\ (b\ xor\ c)$$
再回到這個題上來,因為 $a\ xor\ b\ xor\ b = a$,所以從根節點出來的一條路徑我們可以預先處理一個異或和出來。
在詢問的時候再將多余的路徑給異或掉。設兩點的 LCA 為 z,那么答案就是 $dis[tmp]\ xor\ dis[x]\ xor\ dis[tmp]\ xor\ dis[y]$
有第一條性質 $a\ xor\ b\ xor\ b = a$ 可以化簡上式,答案就變成了 $dis[x]\ xor\ dis[y]$,化簡后我們發現根本就不需要求 LCA。
下面給出代碼。
?
# 代碼
#include <iostream> #include <cstring> #include <cstdio> #include <cmath> using namespace std; const int maxn = 1e5+3; int n, m, head[maxn], cnt, dis[maxn], rt = 1, fa[maxn][32]; struct edge {int to, w, nxt;} ed[maxn << 1]; void read(int &x) {x = 0; int f = 1; char c = getchar();while (c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}while (c <= '9' && c >= '0') {x = x*10 + c-'0'; c = getchar();}x *= f; } struct HAHA {void addedge(int u, int v, int w) {ed[++cnt].nxt = head[u], head[u] = cnt, ed[cnt].to = v, ed[cnt].w = w;}void dfs(int u) {for(int i=head[u]; i; i=ed[i].nxt) {if(ed[i].to == fa[u][0]) continue;dis[ed[i].to] = dis[u] ^ ed[i].w;fa[ed[i].to][0] = u;dfs(ed[i].to);}} }T; int main() {read(n);int x, y, z;for(int i=1; i<n; i++) {read(x), read(y), read(z);T.addedge(x, y, z), T.addedge(y, x, z);}T.dfs(rt);read(m);for(int i=1; i<=m; i++) {read(x), read(y);printf("%d\n", dis[x]^dis[y]);} }?
轉載于:https://www.cnblogs.com/bljfy/p/9776058.html
總結
以上是生活随笔為你收集整理的「 Luogu P2420 」 让我们异或吧的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 彻底弄懂 HTTP 缓存机制及原理 |
- 下一篇: Python是如何进行内存管理的?