码迷,mamicode.com
首页 > 其他好文 > 详细

Highways POJ - 1751

时间:2019-11-08 21:07:56      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:mat   friend   can   algo   return   target   info   scanf   lin   

题目链接:https://vjudge.net/problem/POJ-1751

思路:

最小生成树板子,只需要多记录每个dis[x]的权值是从哪个点到x这个点的。

 1 #include <stdio.h>
 2 #include <iostream>
 3 #include <queue>
 4 #include <math.h>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 const int N = (int)1e3 + 10;
 9 const int inf = (int)1e9;
10 double px[N];
11 double py[N];
12 double g[N][N];
13 bool vis[N];
14 int n,m;
15 int s;
16 
17 struct info{
18     int from;
19     double w;
20 }dis[N];
21 
22 struct node{
23     int loc;
24     double w;
25     bool friend operator<(const node & a,const node& b){
26         return a.w > b.w;
27     }
28 };
29 priority_queue<node > que;
30 
31 inline double dist(int a,int b){
32     return sqrt((px[a]-px[b])*(px[a]-px[b])+(py[a]-py[b])*(py[a]-py[b]));
33 }
34 
35 void build_map(){
36 
37     for(int i = 1; i <= n; i++)
38         for(int j = i + 1; j <= n; j++)
39             g[i][j] = g[j][i] = dist(i,j);
40 
41     for(int i = 1; i <= n; i++) g[i][i] = 0;
42 }
43 
44 void prime(){
45 
46     for(int i = 1; i <= n; i++){
47         vis[i] = 0;
48         dis[i].w = inf;
49     }
50 
51     if(!s) s = 1;
52 
53     que.push(node{s,0});
54     dis[s].from = 0;
55     dis[s].w = 0;
56 
57     while(!que.empty()){
58         int u = que.top().loc;
59         que.pop();
60         vis[u] = 1;
61 
62         for(int v = 1; v <= n; v++){
63             if(!vis[v] && dis[v].w > g[u][v]){
64                 dis[v].w = g[u][v];
65                 dis[v].from = u;
66                 que.push(node{v,dis[v].w});
67             }
68         }
69     }
70 
71     for(int i = 1; i <= n; i++){
72         if(dis[i].w == 0) continue;
73         printf("%d %d\n",dis[i].from,i);
74     }
75 }
76 
77 int main(){
78 
79 
80     scanf("%d",&n);
81 
82     for(int i = 1; i <= n; i++)
83         scanf("%lf%lf",&px[i],&py[i]);
84 
85     build_map();
86 
87     scanf("%d",&m);
88     int u,v;
89 
90     for(int i = 1; i <= m ;i++){
91         scanf("%d%d",&u,&v);
92         s = u;
93         g[u][v] = g[v][u] = 0;
94     }
95 
96     prime();
97     return 0;
98 }

 

Highways POJ - 1751

标签:mat   friend   can   algo   return   target   info   scanf   lin   

原文地址:https://www.cnblogs.com/SSummerZzz/p/11823014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!