畅通工程续
第一次写dijkstra算法
高仿代码如下:
#include <iostream>
#include <string.h>
#include <queue>
#include <vector>
#include <utility>
#include <cstdio>
using namespace std;
#define N 205
#define M 2005
typedef pair<int,int> pii;
int v[M],first[M],d[N],w[M],next[M],e;
void addedge(int a,int b,int x){
v[e]=b;
next[e]=first[a];
w[e]=x;
first[a]=e++;
}
void dijkstra(int st){
priority_queue<pii,vector<pii>,greater<pii> > q;
memset(d,-1,sizeof(d));
d[st]=0;
q.push(make_pair(0,st));
while(!q.empty()){
while(!q.empty() && q.top().first > d[q.top().second]) q.pop();
if(q.empty()) break;
int u = q.top().second;
q.pop();
for(int i = first[u];i != -1;i = next[i]){
if(d[v[i]] == -1 || d[v[i]] > d[u]+w[i]){
d[v[i]] = d[u]+w[i];
q.push(make_pair(d[v[i]],v[i]));
}
}
}
}
int main(){
int n,m,a,b,x;
// freopen("test.txt","r",stdin);
while(cin>>n>>m){
e=0;
memset(first,-1,sizeof(first));
for(int i=0;i<m;i++){
cin>>a>>b>>x;
addedge(a,b,x);
addedge(b,a,x);
}
cin>>a>>b;
dijkstra(a);
cout<<d[b]<<endl;
}
return 0;
}