While this is somewhat pointless with only a few dominoes, some people went to the opposite extreme in the early Eighties. Using millions of dominoes of different colors and materials to fill whole halls with elaborate patterns of falling dominoes, they created (short-lived) pieces of art. In these constructions, usually not only one but several rows of dominoes were falling at the same time. As you can imagine, timing is an essential factor here.
It is now your task to write a program that, given such a system of rows formed by dominoes, computes when and where the last domino falls. The system consists of several ``key dominoes'' connected by rows of simple dominoes. When a key domino falls, all rows connected to the domino will also start falling (except for the ones that have already fallen). When the falling rows reach other key dominoes that have not fallen yet, these other key dominoes will fall as well and set off the rows connected to them. Domino rows may start collapsing at either end. It is even possible that a row is collapsing on both ends, in which case the last domino falling in that row is somewhere between its key dominoes. You can assume that rows fall at a uniform rate.
The following m lines each contain three integers a, b, and l, stating that there is a row between key dominoes a and b that takes l seconds to fall down from end to end.
Each system is started by tipping over key domino number 1.
The file ends with an empty system (with n = m = 0), which should not be processed.
2 1 1 2 27 3 3 1 2 5 1 3 5 2 3 5 0 0
Sample Output
System #1 The last domino falls after 27.0 seconds, at key domino 2. System #2 The last domino falls after 7.5 seconds, between key dominoes 2 and 3.
#include<iostream>
#include<stdio.h>
using namespace std;
const int maxn=505;
const int inf=0x3f3f3f3f;
int n,m,maze[maxn][maxn],dis[maxn];
bool vis[maxn];
void solve(){
for(int i=2;i<=n;i++) dis[i]=maze[1][i],vis[i]=0;
dis[1]=0;
double m1=-1,m2=-1;int p,a,b;
for(int i=1;i<n;i++){
int index,Min=inf;
for(int j=2;j<=n;j++)
if(!vis[j]&&Min>dis[j]) Min=dis[j],index=j;
vis[index]=1;
for(int j=2;j<=n;j++)
if(dis[j]>dis[index]+maze[index][j]) dis[j]=dis[index]+maze[index][j];
}
for(int i=1;i<=n;i++)
if(m1<dis[i]) m1=dis[i],p=i;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(maze[i][j]!=inf&&(dis[i]+dis[j]+maze[i][j])/2.0>m2){
m2=(dis[i]+dis[j]+maze[i][j])/2.0;
a=i;
b=j;
}
if(m1>=m2)
printf("The last domino falls after %.1f seconds, at key domino %d.\n\n",m1,p);
else
printf("The last domino falls after %.1f seconds, between key dominoes %d and %d.\n\n", m2,a,b);
}
int main(){
int cas=0;
while(scanf("%d%d",&n,&m)&&n){
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
maze[i][j]=inf;
for(int u,v,w,i=0;i<m;i++){
scanf("%d%d%d",&u,&v,&w);
maze[u][v]=maze[v][u]=w;
}
printf("System #%d\n",++cas);
solve();
}
}