日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

「 Luogu P2420 」 让我们异或吧

發布時間:2025/3/21 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 「 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 」 让我们异或吧的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。