裸裸的最短路问题,将while(scanf("%d%d", &N, &M)!=EOF)粗心写为while(scanf("%d%d", &N, &M),我还奇怪怎么一直是超时,OMG.
首先用Dijstra算法,寻找两点间最短路径长度,算法复杂度是O(n^2).
#define _CRT_SECURE_NO_DEPRECATE #include<iostream> using namespace std; #define MAX_SIZE 202 #define MAX_NUMBER INT_MAX/2 int dis[MAX_SIZE]; bool visit[MAX_SIZE]; int G[MAX_SIZE][MAX_SIZE]; int N, M; void Dijstra(int s,int t); int main() { int i, j,k,w,s,t; while (scanf("%d%d", &N, &M)!=EOF) { for (i = 0; i < N; i++) { G[i][i] = 0; for (j = i + 1; j < N; j++) G[i][j] = G[j][i] = MAX_NUMBER; } for (k = 0; k < M; k++) { scanf("%d%d%d", &i, &j, &w); if(w<G[i][j]) G[i][j] = G[j][i] = w; } scanf("%d%d", &s, &t); Dijstra(s,t); if (dis[t] != MAX_NUMBER) printf("%d ", dis[t]); else printf("-1 "); } return 0; } void Dijstra(int s,int t) { int i, j, k,pos,lmin; for (i = 0; i < N; i++) { visit[i] = 0; dis[i] = MAX_NUMBER; } j = s; dis[j] = 0; visit[j] = 1; for (i = 0; i < N; i++) { for (k = 0; k <N; k++) { if (!visit[k] && dis[k]>dis[j] + G[k][j]) dis[k] = dis[j] + G[k][j]; } pos =s; lmin = MAX_NUMBER; for (k =0; k <N; k++) { if (!visit[k] && lmin > dis[k]) { pos = k; lmin = dis[k]; } } j = pos; if (j ==s||j==t) return; visit[j] = 1; } }
接着使用Floyd算法也可以解决,时间复杂度是O(n^3),当然在这里是多此一举,不需要求出任意两点间最短距离。
#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
using namespace std;
#define MAX_SIZE 202
#define MAX_NUMBER INT_MAX/2
int dis[MAX_SIZE][MAX_SIZE];
int G[MAX_SIZE][MAX_SIZE];
int N, M;
void Floyd();
int main() {
int i, j, k, w, s, t;
while (scanf("%d%d", &N, &M) != EOF) {
for (i = 0; i < N; i++) {
G[i][i] = 0;
for (j = i + 1; j < N; j++)
G[i][j] = G[j][i] = MAX_NUMBER;
}
for (k = 0; k < M; k++) {
scanf("%d%d%d", &i, &j, &w);
if (w<G[i][j])
G[i][j] = G[j][i] = w;
}
scanf("%d%d", &s, &t);
Floyd();
if (dis[s][t] != MAX_NUMBER)
printf("%d
", dis[s][t]);
else
printf("-1
");
}
return 0;
}
void Floyd() {
int i, j, k;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
dis[i][j] = G[i][j];
for (k = 0; k < N; k++)
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
if (dis[i][j]>dis[i][k] + dis[k][j])
dis[i][j] = dis[i][k] + dis[k][j];
}