http://acm.hdu.edu.cn/showproblem.php?pid=2066
迪杰斯特拉算法实现(400MS):
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 1001;
int V,E,G[1010][1010],dis[1010],vis[1010];
int u[1010],v[1010];
void dijkstra(int scr){
for(int i=0; i<MAX; i++){
dis[i] = G[scr][i];
vis[i] = 0;
}
vis[scr] = 1;
for(int i=0; i<V-1; i++){
int tmp = 1e9, k = scr;
for(int j=1; j<=V; j++){
if(vis[j]) continue;
if(dis[j] < tmp){
tmp = dis[j];
k = j;
}
}
// cout << tmp << endl;
vis[k] = 1;
for(int j=1; j<=V; j++){
if(vis[j]) continue;
dis[j] = min(dis[j], dis[k] + G[k][j]);
}
}
}
int main(){
// freopen("in.txt", "r", stdin);
int a,b;
while(scanf("%d%d%d",&E,&a,&b) == 3){
for(int i=1; i<MAX; i++){
for(int j=1; j<MAX; j++){
G[i][j] = 1e9;
}
G[i][i] = 0;
}
for(int i=0; i<E; i++){
int from,to,cost;
scanf("%d%d%d",&from,&to,&cost);
V = max(V, max(from, to));
G[from][to] = G[to][from] = min(G[from][to],cost);
}
for(int i=0; i<a; i++){
scanf("%d",&u[i]);
}
for(int i=0; i<b; i++){
scanf("%d",&v[i]);
}
int ans = 1e9;
for(int i=0; i<a; i++){
dijkstra(u[i]);
for(int j=0; j<b; j++)
ans = min(ans, dis[v[j]]);
}
printf("%d\n",ans);
}
return 0;
}
SPFA实现(0MS):
#include <queue>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
struct edge{
int to;
int cost;
int next;
}adj[2000010];
int num,head[1010],a,b,c,V;
void addedge(int from, int to, int cost){
adj[num].to = to;
adj[num].cost = cost;
adj[num].next = head[from];
head[from] = num++;
}
int dis[1010],vis[1010],enter[1010];
bool SPFA(int scr){
for(int i=1; i<=V; i++){
dis[i] = 1e9;
vis[i] = 0;
enter[i] = 0;
}
dis[scr] = 0;
vis[scr] = 1;
enter[scr] = 1;
queue <int> Q;
Q.push(scr);
while(!Q.empty()){
int tmp = Q.front();
Q.pop();
vis[tmp] = 0;
for(int i=head[tmp]; i!=-1; i=adj[i].next){
if(dis[adj[i].to] > dis[tmp] + adj[i].cost){
dis[adj[i].to] = dis[tmp] + adj[i].cost;
if(!vis[dis[adj[i].to]]){
vis[adj[i].to] = 1;
enter[adj[i].to]++;
if(enter[adj[i].to] >= V)
return false;
Q.push(adj[i].to);
}
}
}
}
return true;
}
int u[1010],v[1010];
int main(){
// freopen("in.txt", "r", stdin);
while(scanf("%d%d%d",&a,&b,&c) == 3){
memset(head, -1, sizeof(head));
num = 0;
for(int i=0; i<a; i++){
int from, to, cost;
scanf("%d%d%d",&from,&to,&cost);
V = max(V, max(from, to));
addedge(from, to, cost);
addedge(to, from, cost);
}
for(int i=0; i<b; i++)
scanf("%d",&u[i]);
for(int i=0; i<c; i++)
scanf("%d",&v[i]);
int ans = 1e9;
for(int i=0; i<b; i++){
SPFA(u[i]);
for(int j=0; j<c; j++)
ans = min(ans, dis[v[j]]);
}
printf("%d\n",ans);
}
return 0;
}