[ABC396D] Minimum XOR Path

题意

找出带边权的简单连通无向图上一条从顶点 \(1\)\(n\) 边权异或之和最小的路径。

\(2\le n\le 10\)

思路

发现 \(n\le 10\),可以直接 dfs 求出每条路径的异或值,状态数大概是 \(n!\) 的,可以通过本题。

注意边权会超 int,记得开 long long,还有在 dfs 时需要回溯,要重置 vis 数组。

代码

#include <bits/stdc++.h>
#define int long long
using namespace std;
struct node{
	int x,d;
};
int n,m,ans=LONG_LONG_MAX;
bool vis[15];
vector<node> t[15];
void dfs(int x,int xr){
	if(x==n){
		ans=min(ans,xr);
		return;
	}
	vis[x]=true;
	for(node v:t[x]){
		if(!vis[v.x]){
			dfs(v.x,xr^v.d);
		}
	}
	vis[x]=false;
}
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr),cout.tie(nullptr);
	cin>>n>>m;
	for(int x,y,d,i=1;i<=m;i++){
		cin>>x>>y>>d;
		t[x].push_back({y,d});
		t[y].push_back({x,d});
	}
	dfs(1,0);
	cout<<ans;
	return 0; 
}
posted @ 2025-03-26 11:05  WuMin4  阅读(86)  评论(0)    收藏  举报