题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2544
思路:这道题是赤裸裸的最短路径,主要目的是练习并且比较一下dijkstra算法不使用优先队列和使用优先队列的速度差距
不使用优先队列:
///2014.7.14
///hdu2544
//2014-07-14 23:13:58 Accepted 2544 15MS 372K 1195 B G++
//赤裸裸的dijkstra
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int MAXINT = 2147483647;
int n,m;
int edge[110][110];
int dist[110];
void init(){
for(int i=1 ; i<=n ; i++)
dist[i] = MAXINT;
for(int i=0 ; i<=n ; i++)
for(int j=0 ; j<=n ; j++)
edge[i][j] = -1;
int a,b,c;
for(int i=0 ; i<m ; i++){
scanf("%d %d %d",&a,&b,&c);
edge[a][b] = edge[b][a] = c;
}
}
void dijkstra(int source){
queue<int> que;
que.push(source);
dist[source] = 0;
while( !que.empty() ){
int p = que.front();
que.pop();
for(int i=1 ; i<=n ; i++){
if( edge[p][i] != -1 ){
if( dist[p]+edge[p][i] < dist[i] ){
dist[i] = dist[p]+edge[p][i];
que.push(i);
}
}
}
}
}
int main(){
// freopen("in","r",stdin);
// freopen("out","w",stdout);
while( scanf("%d %d",&n,&m) && n ){
init();
dijkstra(1);
printf("%d\n",dist[n]);
}
return 0;
}
下面是使用STL中priority_queue“优化”的代码,速度还是15MS,时间是一样的。是数据太水了还是我写的代码太水了,根本就没有领悟到该怎么做。。。 ::>_<::
///2014.7.15
///hdu2544
//2014-07-15 09:33:08 Accepted 2544 15MS 388K 1583 B G++
//赤裸裸的dijkstra,使用优先队列优化
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int MAXINT = 2147483647;
int n,m;
int edge[110][110];
int dist[110];
void init(){
for(int i=1 ; i<=n ; i++)
dist[i] = MAXINT;
for(int i=0 ; i<=n ; i++)
for(int j=0 ; j<=n ; j++)
edge[i][j] = -1;
int a,b,c;
for(int i=0 ; i<m ; i++){
scanf("%d %d %d",&a,&b,&c);
edge[a][b] = edge[b][a] = c;
}
}
struct E
{
int num,dist;
};
bool operator< (E a,E b){
return a.dist > b.dist;
}
void dijkstra(int source){
bool finded[110];
memset(finded,false,sizeof(finded));
priority_queue<E> que;
E p;
p.num = source;
p.dist = 0;
que.push(p);
dist[source] = 0;
while( !que.empty() ){
E p = que.top();
que.pop();
finded[p.num] = true;
for(int i=1 ; i<=n ; i++){
if( finded[i] ) continue;
if( edge[p.num][i] != -1 ){
if( dist[p.num]+edge[p.num][i] < dist[i] ){
dist[i] = dist[p.num]+edge[p.num][i];
E q;
q.num = i,q.dist = dist[i];
que.push(q);
}
}
}
}
}
int main(){
// freopen("in","r",stdin);
// freopen("out","w",stdout);
while( scanf("%d %d",&n,&m) && n ){
init();
dijkstra(1);
printf("%d\n",dist[n]);
}
return 0;
}