链接:http://poj.org/problem?id=1135
题意:dijkstra算法的应用。
思路:先找到从第一个点出发到所有点的单源最短路,选择最长的一个。如果某两个点之间的多米诺骨牌传播时间终止点在最长的最短路时间之后,就把该点确定为所需时间。
用“%lf” G++ wa,C++ac.
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<ctype.h>
#include<algorithm>
#include<string>
#define PI acos(-1.0)
#define maxn 505
#define maxm 30005
#define INF 1<<25
typedef long long ll;
using namespace std;
int point [maxn];
int vv[maxn];
double dis[maxn];
struct Edge
{
int v;
double w;
int next;
} edge[maxm];
int top;
int init()
{
top=0;
memset(point,-1,sizeof(point));
return 0;
}
int add_edge(int x,int v,double w)
{
edge[top].v=v;
edge[top].w=w;
edge[top].next=point[x];
point[x]=top++;
edge[top].v=x;
edge[top].w=w;
edge[top].next=point[v];
point[v]=top++;
return 0;
}
struct node
{
int v,w;
node(int _v,int _w):v(_v),w(_w) {}
bool operator < (const node &a)const
{
return a.w<w;
}
};
int main()
{
int tot,tt;
int jj=1;
while(scanf("%d%d",&tot,&tt))
{
memset(vv,0,sizeof(vv));
init();
bool jud=0;
double ans=0;
int aa,bb,cc,ra=1;
if(tot==0&&tt==0)
return 0;
for(int i=0; i<tt; i++)
{
int v1,v2,w;
scanf("%d%d%d",&v1,&v2,&w);
add_edge(v1,v2,w);
}
priority_queue < node > qq;
memset(vv,0,sizeof(vv));
for(int i=1; i<=tot; i++)
{
dis[i]=INF;
}
dis[1]=0;
qq.push(node(1,0));
printf("System #%d\n",jj++);
while(!qq.empty())
{
node rec=qq.top();
qq.pop();
if(vv[rec.v]==1)
continue;
vv[rec.v]=1;
for(int i=point[rec.v]; i!=-1; i=edge[i].next)
{
int v=edge[i].v;
int w=edge[i].w;
if(dis[v]>dis[rec.v]+edge[i].w&&dis[rec.v]!=INF)
{
dis[v]=dis[rec.v]+edge[i].w;
qq.push(node(v,dis[v]));
}
}
}
for(int i=2; i<=tot; i++)
{
if(dis[i]>ans)
{
ans=dis[i];
ra=i;
}
}
for(int ii=1; ii<=tot; ii++)
{
for(int i=point[ii]; i!=-1; i=edge[i].next)
{
int v=edge[i].v;
int w=edge[i].w;
if(dis[ii]<=dis[v])
{
double num=dis[v]+(w+dis[ii]-dis[v])/2;
if(num>ans)
{
jud=1;
aa=ii;
bb=v;
ans=num;
}
}
}
}
if(jud==0)
printf("The last domino falls after %.1lf seconds, at key domino %d.\n",ans,ra);
else
{
if(aa>bb) swap(aa,bb);
printf("The last domino falls after %.1lf seconds, between key dominoes %d and %d.\n",ans,aa,bb);
}
printf("\n");
}
}