CCF 201609-4 交通規劃 (迪傑斯特拉+優先佇列)
阿新 • • 發佈:2018-12-10
這道題我沒有好的思路,剛開始用的是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]; } }