Codeforces Round #835 (Div. 4) G. SlavicG’s Favorite Problem
Let’s ignore the teleporting, and decide how to find the answer. Note that we don’t need to ever go over an edge more than once, since going over an edge twice cancels out (since a a a XOR a = 0 a=0 a=0 for all a). In other words, the only possible value of x x x equals the XOR of the edges on the unique path from a a a to b b b. We can find it through a a a BFS from a a a, continuing to keep track of XOR s as we move to each adjacent node, and XOR ing it by the weight of the corresponding edge as we travel across it.
Now let’s include the teleport. It means that we travel from a → c a→c a→c, then teleport to d d d, and go from d → b d→b d→b, for some nodes c c c and d d d. Also, we cannot pass b b b on the path from a → c a→c a→c.
Again, note that the value of x x x is fixed on each of the paths from a → c a→c a→c and d → b d→b d→b, since there is a a a unique path between them. Let x 1 x_1 x1 be the XOR of the first path and x 2 x_2 x2 be the XOR of the second. Then we need x 1 x_1 x1 XOR x 2 = 0 x2=0 x2=0 ⟹ ⟹ ⟹ x 1 = x 2 x_1=x_2 x1=x2. So we need to find if there are two nodes c c c, d d d such that the XORs from a and b to those nodes are the same. To do this, we can do our BFS from before, but instead run one BFS from a and another from b b b, and check if any two values are the same.
Make sure not to include nodes past b b b while we look for c c c on our BFS from a a a.
The time complexity is O ( n l o g n ) O(nlogn) O(nlogn).
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
int main()
{
int T=1;cin>>T;
while(T--)
{
int n,a,b;cin>>n>>a>>b;
vector<vector<PII>> g(n+1);
for(int i=1;i<=n-1;i++)
{
int u,v,w;cin>>u>>v>>w;
g[u].push_back({v,w});
g[v].push_back({u,w});
}
vector<vector<int>> f(2,vector<int>(n+1));
function<void(int,int,int,int)> dfs=[&](int u,int val,int id,int fa)
{
f[id][u]=val;
for(auto &[v,p]:g[u])
{
if(v==fa || v==b) continue;
dfs(v,val^p,id,u);
}
};
dfs(a,0,0,-1);
dfs(b,0,1,-1);
set<int> st;
for(int i=1;i<=n;i++)
st.insert(f[0][i]);
bool ok=false;
for(int i=1;i<=n;i++)
if(i!=b && st.count(f[1][i]))
ok=true;
if(ok) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}