CF1076D 最短路樹

題意:n個點m條邊,最多可以刪除m-k條邊,使得剩下的邊爲構成原圖的最短路樹。
思路:dij之後跑一邊dfs最短路樹。
代碼:

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define forn(i,n) for(int i=0;i<n;i++)
#define for1(i,n) for(int i=1;i<=n;i++)
#define IO ios::sync_with_stdio(false);cin.tie(0)
const int maxn = 3e5+5;
const ll inf = 2e18+5;
#pragma GCC optimize(2)
int n,m,k;
struct node{
    int w,id,p;
}nd[maxn];
ll d[maxn];
bool vis[maxn];
vector<node>e[maxn];

void dfs(int u){
    vis[u] = 1;
    for(auto &x:e[u]){
        int v = x.p,id = x.id,w = x.w;
        if(!vis[v]&&d[v]==d[u]+w){
            if(!k) return;
            cout<<id<<' ';
            k--;
            dfs(v);
        }
    }    
}

int main(){
    IO;
    forn(i,maxn) d[i] = inf;
    cin>>n>>m>>k;
    for1(i,m){
        int x,y,z;cin>>x>>y>>z;
        e[x].push_back({z,i,y});
        e[y].push_back({z,i,x});
    }
    priority_queue<pair<ll,int> > q;
    q.push({0,1});
    d[1] = 0;
    while(!q.empty()){
        auto now = q.top();q.pop();
        int u = now.second;
        if(vis[u]) continue;
        vis[u] = 1;
        for(auto &x:e[u])if(!vis[x.p]){
            int v = x.p,w = x.w;
            if(d[v]>d[u]+w){
                d[v]=d[u]+w;
                q.push({-d[v],v});
            }
        }
    }
    forn(i,maxn) vis[i] = 0;
    cout<<min(n-1,k)<<'\n';
    vector<int>ans;
    dfs(1);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章