#include <iostream>
#include <cstdio>
#include <vector>
#define Min(x,y) ( (x) < (y) ? (x) : (y) )
using namespace std;
const int maxn = 205;
const int INF = 0x3f3f3f3f;
struct Node
{
int vex,weight;
Node(int _vex = 0,int _weight = 0) : vex(_vex),weight(_weight){}
};
vector<Node> G[maxn];
bool intree[maxn];
int mindist[maxn],n,m;
void Init()
{
for(int i = 0 ; i < maxn ; ++i){
G[i].clear();
mindist[i] = INF;
intree[i] = false;
}
}
int Dijkstra(int s,int e)
{
int ans = 0;
int vex,addNode,tempMin;//加入集合F中的节点
intree[s] = true;//加入生成树
for(unsigned int i = 0 ; i < G[s].size() ; ++i){
vex = G[s][i].vex;
mindist[vex] = Min(mindist[vex],G[s][i].weight);
}//寻找与当前节点相连的最小点
mindist[s] = 0;//s到s的距离为自身
for(int nodeNum = 1 ; nodeNum <= n - 1 ; ++nodeNum){//找到那个点把他加入
tempMin = INF;
for(int i = 0 ; i < n ; ++i){//编号0-n-1
if(intree[i] == false && mindist[i] < tempMin){
tempMin = mindist[i];
addNode = i;
}
}
intree[addNode] = true;//addNode 加入集合F
for(unsigned int i = 0 ; i < G[addNode].size() ; ++i){//找到这个点的相邻点并且更新所有值
vex = G[addNode][i].vex;
if(intree[vex] == false && mindist[addNode] + G[addNode][i].weight < mindist[vex])//
mindist[vex] = mindist[addNode] + G[addNode][i].weight;
}
}
return mindist[e];
}
int main()
{
int v1,v2,weight,s,e;
while(scanf("%d%d",&n,&m) != EOF)
{
Init();
for(int i = 0 ; i < m ; i++){
scanf("%d%d%d",&v1,&v2,&weight);
G[v1].push_back(Node(v2,weight));
G[v2].push_back(Node(v1,weight));
}
scanf("%d%d",&s,&e);
int ans = Dijkstra(s,e);
if(ans == INF)
printf("%d\n",-1);
else
printf("%d\n",ans);
}
return 0;
}
以上版本 太复杂
heap 优化版本
// hdu1874 效率 (E + n)log(n);
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
#define maxn 200 + 10
#define INF 0x3f3f3f3f
using namespace std;
struct node{
int v,len;
node(int v = 0, int len = 0):v(v),len(len){}
friend bool operator < (const node &a,const node &b)
{
return a.len > b.len;
}
};
vector<node>G[maxn];
bool vis[maxn];
int dis[maxn];
void init(){
for(int i=0;i<maxn;i++){
G[i].clear();
vis[i] = false;
dis[i] = INF;
}
}
int dijkstra_heap(int s,int e){
priority_queue<node>Q;
Q.push(node(s,0));
dis[s] = 0;
while(!Q.empty()){
node now = Q.top();
Q.pop();
int v = now.v;
if(vis[v]) continue; //如果标记过了 直接continue
vis[v] = true;
for(int i=0;i<G[v].size();i++){
int v2 = G[v][i].v;
int len = G[v][i].len;
if(!vis[v2] && dis[v2] > dis[v] + len){
dis[v2] = dis[v] + len;
Q.push(node(v2,dis[v2]));
}
}
}
return dis[e];
}
int n,m;
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
init();
for(int i=0;i<m;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
G[a].push_back(node(b,c));
G[b].push_back(node(a,c));
}
int s,t;
scanf("%d%d",&s,&t);
int ans = dijkstra_heap(s,t);
if(ans == INF)
printf("-1\n");
else
printf("%d\n",ans);
}
return 0;
}