您的位置:首页 > 其它

HDU 2544 最短

2015-08-18 10:00 417 查看
链接:http://acm.hdu.edu.cn/showproblem.php?

pid=2544

解析

首先数据量为V<=100

那么这里使用不论什么基础的最短路的算法都不会超时!

常见数据

5 6
1 2 10
1 3 4
2 4 2
3 4 3
2 5 5
4 5 100
// 答案:14

2 4
1 2 10
1 3 4
2 4 2
3 4 3
// 答案:9


Bellman-Ford算法

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
using namespace std;
#define MAX_E 10010
#define MAX_V 105
#define INF 1e8

struct edge{int from, to, cost; };
edge es[2*MAX_E];
int d[MAX_V];
int V, E;

void shortest_path(int s){
for(int i=1; i<=V; ++i) d[i] = INF;
d[s] = 0;
while(true){
bool update = false;
for(int i=0; i<2*E; ++i){
edge e = es[i];
if(d[e.from] != INF&&d[e.to]>d[e.from]+e.cost){
d[e.to] = d[e.from] + e.cost;
update = true;
}
}
if(!update) break;

}
}

int main(){
while(~scanf("%d%d", &V, &E), V||E){
int i;
int a,b,c;

for(i=0; i<E; ++i){
scanf("%d%d%d", &a, &b, &c);
es[i].from = a; es[i].to = b; es[i].cost = c;
es[i+E].from = b; es[i+E].to = a; es[i+E].cost = c;
}
shortest_path(1);
printf("%d\n", d[V]);
}
}


Dijkstra算法

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
#define MAX_V 105
#define MAX_X 105
#define INF 1e8

int cost[MAX_V][MAX_V];
int d[MAX_X];
bool used[MAX_X];
int n,m;

void dijkstra(int s){
for(int i=1; i<=n; ++i){
d[i] = INF;
used[i] = false;
}
d[s] = 0;

while(true){
int v = -1;
for(int u=1; u<=n; ++u){
if(!used[u]&&(v==-1||d[u]<d[v])) v = u;
}
if(v == -1) break;
used[v] = true;
for(int u=1; u<=n; ++u){
d[u] = min(d[u], d[v]+cost[v][u]);
}
}
}

int main(){
while(~scanf("%d%d", &n, &m), m||n){
int i;
int a,b,c;

for(i=1; i<=n; ++i)
for(int j=1; j<=n; ++j)
cost[i][j] = INF;

for(i=0; i<m; ++i){
scanf("%d%d%d", &a, &b, &c);
cost[a] = c;
cost[b][a] = c;
}
dijkstra(1);
printf("%d\n", d
);
}
}


[b]Floyd算法


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
using namespace std;
#define MAX_V 105
#define MAX_X 105
#define INF 1e8

int d[MAX_V][MAX_V];
bool used[MAX_X];
int n,m;

void floyd(){
for(int k=1; k<=n; ++k){
for(int i=1; i<=n; ++i){
for(int j=1; j<=n; ++j){
d[i][j] = min(d[i][j], d[i][k]+d[k][j]);
}
}
}
}

int main(){
while(~scanf("%d%d", &n, &m), m||n){
int i;
int a,b,c;

for(i=1; i<=n; ++i)
for(int j=1; j<=n; ++j)
d[i][j] = INF;
for(i=1; i<=n; ++i) d[i][i] = 0;

for(i=0; i<m; ++i){
scanf("%d%d%d", &a, &b, &c);
d[a][b] = c;
d[b][a] = c;
}
floyd();
printf("%d\n", d[1]
);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: