http://acm.hdu.edu.cn/showproblem.php?pid=1874 浙大上机真题,畅通工程续 |
#include<vector>
#include<cstdio>
#include<climits>
#include<queue>
#define N 300
using namespace std ;
struct Edge{
int y;
int weight;
};
struct Node{
int dist;
int x;
};
bool operator <(Node lhs , Node rhs){
return lhs.dist > rhs.dist;
}
vector<Edge> graph[N];
int dijkstra(int s, int t, int n){
int dist[N];
bool Isvisit[N];
for(int i = 0 ; i < n ; ++i){
dist[i] =INT_MAX;
Isvisit[i] = false;
}
priority_queue<Node> myQue;//首次访问到某个结点,再把他加入到优先队列中
//第一个是起点
dist[s] = 0;
Node node;
node.dist = dist[s];
node.x = s;
myQue.push(node);
while(myQue.empty() == false){
int x = myQue.top().x ;//小根堆堆顶编号
myQue.pop();
if(Isvisit[x] == true){
continue;
}
Isvisit[x] = true;
for(int i = 0 ; i < graph[x].size() ; ++i){
//找与x关联的边
int y = graph[x][i].y;
int weight = graph[x][i].weight;
if(dist[y] > dist[x] + weight){
dist[y] = dist[x] + weight;
node.dist = dist[y] ;
node.x = y;
myQue.push(node);
}
}
}
if(dist[t] != INT_MAX){
return dist[t] ;
}else{
return -1;
}
}
int main(){
int n , m ;
while(scanf("%d%d",&n,&m) != EOF){
for(int i = 0 ; i < n ; ++i){
graph[i].clear();//清空
}
for(int i = 0; i < m ; ++i){
int x,y,weight;
scanf("%d%d%d",&x,&y,&weight);
Edge edge;
edge.y = y;
edge.weight = weight;
graph[x].push_back(edge);
edge.y = x;
edge.weight = weight;
graph[y].push_back(edge);
}
int s,t;
scanf("%d%d",&s,&t);//起点终点
printf("%d\n", dijkstra(s,t,n));
}
}