这道题因为循环判断语句WA了三十多发,生活完全无法自理.
卒
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define INF 100000100 //无穷大
#define MAXN 550 //顶点个数的最大值
int n,m; //顶点个数
int Edge[MAXN][MAXN]; //邻接矩阵
int S[MAXN]; //Dijkstra算法用到的三个数组
int dist[MAXN];
int caseno = 1;
void Dijkstra(int v0)
{
int i,j;
for(i = 1;i <= n;i++){
dist[i] = Edge[v0][i];
S[i] = 0;
}
S[v0] = 1; //顶点v0加入到顶点集合S
for(i = 1;i < n;i++){
int min = INF,u;
//选择当前集合T中具有最短路径的顶点u
for(j = 1;j <= n;j++){
if(!S[j]&&dist[j] < min){
u = j; min = dist[j];
}
}
S[u] = 1;
for(j = 1;j <= n;j++){
if(!S[j] && Edge[u][j] != INF&&dist[u]+Edge[u][j] < dist[j]){
dist[j] = dist[u] + Edge[u][j];
}
}
}
double maxtime1 = -INF,maxtime2 = -INF;
int pos,pos1,pos2; //最后倒下的关键时间及位置
for(i = 1;i <= n;i++){
if(dist[i] > maxtime1){
maxtime1 = dist[i]; pos = i;
}
}
//每一行中间普通牌倒下的时间最大值及位置
for(i = 1;i <= n;i++){
for(j = i+1;j <= n;j++){
double t = (dist[i]+dist[j]+Edge[i][j])/2.0;
if(Edge[i][j] < INF&&t > maxtime2){
maxtime2 = t;
pos1 = i;
pos2 = j;
}
}
}
if(maxtime2 > maxtime1)
printf("The last domino falls after %.1f seconds, between key dominoes %d and %d.\n\n",maxtime2,pos1,pos2);
else printf("The last domino falls after %.1f seconds, at key domino %d.\n\n",maxtime1,pos);
}
int main()
{
while (~scanf("%d%d", &n, &m) && (n||m)) {
memset(Edge,0,sizeof(Edge));
int i,j;//读入顶点个数n,边数
int u,v,w; //边的起点和终点及权值
for(i = 1;i <= m ;i++){
scanf("%d%d%d",&u,&v,&w); //读入边的起点和终点,权值
Edge[u][v] = Edge[v][u] = w; //构造邻接矩阵
}
for(i = 1;i <= n;i++){
for(j = i;j <= n;j++){
if(j == i) Edge[i][j] = 0;
else if(Edge[i][j] == 0)Edge[i][j] = Edge[j][i] = INF;
}
}
printf("System #%d\n",caseno++);
Dijkstra(1); //求顶点0到其他顶点的最短路径
}
return 0;
}