最短路-虚拟节点

思路:我们可以开虚拟节点来连接两个结点权值二进制1的个数相同的两个结点,由于1e9内1的个数不超过30,所以开30个虚拟节点,第i个结点连向二进制1的个数为i的点,然后跑dij即可。

代码:

int n, m;
struct d
{
    int u, w;
};

int f(int x){
    int cnt = 0;
    while(x){
        if(x & 1)
            cnt ++;
        x /= 2;
    }
    return cnt;
}
vector<d>e[100100];
int c[100010], dist[100010], st[100010];
const int C = 100010;

void dij(){
    priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>q;
    memset(dist,0x3f,sizeof dist);
    q.push({0, 1});
    dist[1] = 0;
    while(q.size()){
        auto t = q.top();
        q.pop();
        int d = t.first, u = t.second;
        if(st[u])
            continue;
        st[u] = 1;
        for(auto [x,w] : e[u]){
            if(d + w < dist[x]){
                dist[x] = d + w;
                q.push({x,dist[x]});
            }
        }
    }
}

void solve(){
    cin >> n >> m;
    for(int i = 1;i <= n;i ++){
        cin >> c[i];
        e[i].push_back({f(c[i]) + C, c[i]});
        e[f(c[i]) + C].push_back({i, 0});
    }
    for(int i = 0;i < m;i ++){
        int u,v,w;
        cin >> u >> v >> w;
        e[u].push_back({v,w});
        e[v].push_back({u,w});
    }
    dij();
    if(dist[n] == 0x3f3f3f3f)
        cout << "gou yun hao";
    else
        cout << dist[n];
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

临江浪怀柔ℳ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值