Dijkstra最短路
模拟每个key的坠落时间,发现就是Dijkstra。
求出每个key的时间求其最大值,再求每条边整个坠落的时间,求其最大值,得二者最大值即结果。
其中每条边的坠落事件为tv+(cost-(tv-tu))/2,其中u,v为边的两个key节点,tv>tu,cost为边的权值
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 const int maxn=500+10; 7 const int inf=0x3f3f3f3f; 8 const int maxm=maxn*maxn; 9 struct Edge 10 { 11 int to,next,cost,from,dis; 12 }; 13 struct HeapNode 14 { 15 int d,u; 16 bool operator < (const HeapNode& rhs) const { return d>rhs.d; } 17 }; 18 Edge edge[maxm]; 19 int head[maxn],dis[maxn],vis[maxn]; 20 int n,m,tot,loc; 21 double maxv; 22 void dijkstra() 23 { 24 priority_queue<HeapNode> q; 25 memset(dis,inf,sizeof(dis)); 26 memset(vis,0,sizeof(vis)); 27 dis[1]=0; 28 maxv=0; 29 loc=1; 30 q.push((HeapNode){0,1}); 31 while(!q.empty()) 32 { 33 HeapNode x=q.top(); q.pop(); 34 int u=x.u; 35 if(vis[u]) continue; 36 if(dis[u]>maxv) 37 { 38 maxv=dis[u]; 39 loc=u; 40 } 41 vis[u]=1; 42 for(int i=head[u];i!=-1;i=edge[i].next) 43 { 44 if(dis[edge[i].to]>(dis[u]+edge[i].cost)) 45 { 46 dis[edge[i].to]=dis[u]+edge[i].cost; 47 q.push((HeapNode){dis[edge[i].to],edge[i].to}); 48 } 49 } 50 } 51 } 52 int main() 53 { 54 int cas=0; 55 while(scanf("%d%d",&n,&m)) 56 { 57 if(!n&&!m) break; 58 tot=0; 59 memset(head,-1,sizeof(head)); 60 int i; 61 int u,v,cost; 62 for(i=0;i<m;i++) 63 { 64 scanf("%d%d%d",&u,&v,&cost); 65 edge[tot].cost=cost; edge[tot].to=v; edge[tot].from=u; 66 edge[tot].next=head[u]; head[u]=tot++; 67 edge[tot].cost=cost; edge[tot].to=u; edge[tot].from=v; 68 edge[tot].next=head[v]; head[v]=tot++; 69 } 70 dijkstra(); 71 int loc1,loc2,flag=0; 72 double tem; 73 for(i=0;i<tot;i+=2) 74 { 75 tem=(edge[i].cost+dis[edge[i].from]+dis[edge[i].to])/2.0; 76 if(tem>maxv) 77 { 78 flag=1; 79 maxv=tem; 80 loc1=min(edge[i].from,edge[i].to); 81 loc2=max(edge[i].from,edge[i].to); 82 } 83 } 84 printf("System #%d ",++cas); 85 if(flag) printf("The last domino falls after %.1f seconds, between key dominoes %d and %d. ",maxv,loc1,loc2); 86 else printf("The last domino falls after %.1f seconds, at key domino %d. ",maxv,loc); 87 printf(" "); 88 } 89 return 0; 90 }