UVa 10147 - Highways

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

題目網址
中文網址

Solution

將已建好的邊權重設為 0,接著做 MST 即可。

Code

UVa 10147UVa 10147 - Highways
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include<cstdio>
#include<utility>
#include<cmath>
#include<vector>
#include<queue>
#include<functional>
#define N 750
using namespace std;
typedef pair<int, int> Coord;

struct Node
{
int a;//idx of coord[]
double dis;
Node(){}
Node(int aa, double d) :a(aa), dis(d){}
bool operator >(const Node& n)const{ return dis > n.dis; };
};

vector<Node> adjList[N];
double getDistance(Coord& a, Coord& b);
void prim(int n);
int main()
{
Coord coord[N];
int Case;
scanf("%d", &Case);
while (Case--)
{
int n, m, i;
scanf("%d", &n);
for (i = 0; i < n; i++)
adjList[i].clear();
for (i = 0; i < n; i++)
scanf("%d%d", &coord[i].first, &coord[i].second);

//建邊
for (i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
{
double dis = getDistance(coord[i], coord[j]);
adjList[i].push_back(Node(j, dis));
adjList[j].push_back(Node(i, dis));
}

int a, b;
scanf("%d", &m);
//已經建好的邊,權重設為 0
for (i = 0; i < m; i++)
{
scanf("%d%d", &a, &b);
adjList[a - 1].push_back(Node(b - 1, 0));
adjList[b - 1].push_back(Node(a - 1, 0));
}

prim(n);

if (Case)
putchar('\n');
}

return 0;
}
double getDistance(Coord& a, Coord& b)
{
return sqrt((a.first - b.first)*(a.first - b.first) + (a.second - b.second)*(a.second - b.second));
}
void prim(int n)
{
int parent[N] = {}, i;
double d[N] = {};
bool isVisit[N] = {}, flag = true;
for (i = 0; i < n; i++)
d[i] = 1e9;
priority_queue<Node, vector<Node>, greater<Node> > PQ;
PQ.push(Node(0, 0));
d[0] = 0;

for (i = 0; i < n; i++)
{
Node next;
while (isVisit[(next = PQ.top()).a])
PQ.pop();

//新建的路
if (next.dis)
{
printf("%d %d\n", parent[next.a] + 1, next.a + 1);
flag = false;
}

isVisit[next.a] = true;
int size = adjList[next.a].size();
for (int k = 0; k < size; k++)
{
Node node = adjList[next.a][k];
if (!isVisit[node.a] && node.dis < d[node.a])
{
d[node.a] = node.dis;
parent[node.a] = next.a;
PQ.push(node);
}
}
}

if (flag)
puts("No new highways need");
}