poj 1135 Domino Effect
留下代码
有空写解题报告 蛋疼的题目
#include<stdio.h>
const int MAXN = 501;
const int INF = 0x3f3f3f3f;
int n, m;
int map[MAXN][MAXN], dist[MAXN];
bool used[MAXN];
void dijkstra(){
for(int i = 1; i <= n; ++i){
dist[i] = map[1][i];
used[i] = false;
}
used[1] = true;
dist[1] = 0;
for(int i = 1; i < n; ++i){
int min = INF, minidx;
for(int j = 1; j <= n; ++j){
if(!used[j] && min > dist[j])
min = dist[minidx = j]; //这种写法不错 简洁 也易懂
}
used[minidx] = true;
for(int j = 1; j <= n; ++j){
if(!used[j] && dist[j] > dist[minidx] + map[minidx][j])
dist[j] = dist[minidx] + map[minidx][j];
}
}
}
int main(){
int a, b, c ,cases = 1;;
while(scanf("%d%d",&n, &m) == 2, n){
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
map[i][j] = INF;
}
map[i][i] = 0;
}
for(int i = 0; i < m; ++i){
scanf("%d%d%d",&a, &b, &c);
map[a][b] = map[b][a] = c;
}
dijkstra();
int max = dist[1], key = 1, aa, bb;//k置为1 对付n=1,m=0 这组数据
bool flag = true;
for(int i = 2; i <= n; ++i)
if(max < dist[i])
max = dist[key = i];
max *= 2;
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
if( map[i][j] != INF && dist[j] < map[i][j] + dist[i]){
if(dist[i] + dist[j] + map[i][j] > max){
max = dist[aa = i] + dist[bb = j] + map[i][j];
flag = false;
if(a > b)
a ^= b ^= a ^= b;
}
}
}
}
printf("System #%d\n",cases++);
if(flag)
printf("The last domino falls after %d.0 seconds, at key domino %d.\n",max / 2, key);
else
printf("The last domino falls after %.1lf seconds, between key dominoes %d and %d.\n",(double)max / 2, aa , bb );
printf("\n");
}
return 0;
}