CCF 201609-4 交通规划 (迪杰斯特拉+优先队列)

这道题我没有好的思路,刚开始用的是spfa打的,结果不行。

之前没见过迪杰斯特拉+队列优化。

但这确实挺好用,。要是最小生成树跟最短路结合起来的话用这个跑最好不过了。

所以对这道题非常适用。

#include<bits/stdc++.h>

using namespace std;

#define inf 0x3f3f3f3f

const int N=1e4+10;

struct node{
    int to;
    int w;
    int next;
}g[100*N];

int dis[N];
bool vis[N];
int head[N];
int n,m,len;
int cost[N];

inline void addedge(int u,int v,int w){
    g[len].to=v;
    g[len].w=w;
    g[len].next=head[u];
    head[u]=len++;
}

struct Node{
    int v;
    int cost;        // 花费。
    friend bool operetor < (Node a,Node b){
        return a.cost>b.cost;
    }
    Node(int v,int cost):v(v),cost(cost){}
};

void spfa(int u){
    memset(vis,false,sizeof vis);
    memset(dis,inf,sizeof dis);
    memset(cost,inf,sizeof cost);
    priority_queue<Node> q;
    q.push(Node(u,0));
    vis[u]=true;
    dis[u]=cost[u]=0;
    while(!q.empty()){
        int v=q.top().v;
        int cst=q.top.cost;
        q,pop();
        vis[v]=0;
        for(int i=head[u];~i;i=g[i].next){
            int to=g[i].to;
            int w=g[i].w;
            if(dis[to]>dis[u]+w){
                dis[to]=dis[u]+w;
                cost[to]=w;
                if(!vis[to]){
                    q.push(Node(to,w));
                    vis[to]=1;
                }
            }
            if(dis[to]==dis[u]+w){
                cost[to]=min(cost[to],w);
            }
        }
    }
    
}

int main(){
    int u,v,w;
    scanf("%d%d",&n,&m);
    len=0;
    memset(head,-1,sizeof head);
    for(int i=0;i<m;i++){
        scanf("%d%d%d",&u,&v,&w);
        addedge(u,v,w);
        addedge(v,u,w);
    }
    spfa(1);
    int ans=0;
    for(int i=2;i<=n;i++){
        anms+=cost[i];
    }
    
}

猜你喜欢

转载自blog.csdn.net/qq_40679299/article/details/82721885
今日推荐