Shortest Path Problem?线性基

本文介绍了一个特殊的最短路径问题,即在一个带权重的无向图中寻找从节点1到节点n的路径,路径长度定义为所有经过边的权重进行按位异或操作的结果。文章提供了一段C++代码实现,通过深度优先搜索算法来解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

G. Shortest Path Problem?
time limit per test
3 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

You are given an undirected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times). You have to find the minimum length of path between vertex 1 and vertex n.

Note that graph can contain multiple edges and loops. It is guaranteed that the graph is connected.

Input

The first line contains two numbers n and m (1 ≤ n ≤ 100000, n - 1 ≤ m ≤ 100000) — the number of vertices and the number of edges, respectively.

Then m lines follow, each line containing three integer numbers x, y and w (1 ≤ x, y ≤ n, 0 ≤ w ≤ 108). These numbers denote an edge that connects vertices x and y and has weight w.

Output

Print one number — the minimum length of path between vertices 1 and n.

Examples
Input
Copy
3 3
1 2 3
1 3 2
3 2 0
Output
Copy
2
Input
Copy
2 2
1 1 3
1 2 3
Output
Copy
0

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
#define ll long long

vector<pair<int,int> >graph[N];

bool vis[N];
int comps;
int val[N];
int comp[N];
void dfs(int node){
    vis[node]=1;
    for(auto it:graph[node]){
        if(!vis[it.first]){
            val[it.first]=val[node]^it.second;
            dfs(it.first);
        }else{
            comp[++comps]=val[it.first]^val[node]^it.second;
        }
    }
}

vector<int> base;

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen("in.txt","r",stdin);
    //cout<<"1"<<endl;
    int n,m;
    cin>>n>>m;
    for(int i=0;i<m;i++){
        int a,b,c;
        cin>>a>>b>>c;
        graph[a].push_back(make_pair(b,c));
        graph[b].push_back(make_pair(a,c));
    }

    dfs(1);

    for(int i=1;i<=comps;i++){
        int x=comp[i];
        for(auto &t:base)
            x=min(x,x^t);
        if(!x)continue;
        base.push_back(x);
    }
    int ans=val[n];
    for(auto &t:base){
        ans=min(ans,ans^t);
    }
    cout<<ans<<endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值