PAT「1001 Battle Over Cities - Hard Version (35分)」
1. 题目
题目链接:PAT「1001 Battle Over Cities - Hard Version (35分)」 。
Description
It is vitally important to have all the cities connected by highways in a war. If a city is conquered by the enemy, all the highways from/toward that city will be closed. To keep the rest of the cities connected, we must repair some highways with the minimum cost. On the other hand, if losing a city will cost us too much to rebuild the connection, we must pay more attention to that city.
Given the map of cities which have all the destroyed and remaining highways marked, you are supposed to point out the city to which we must pay the most attention.
Input Specification:
Each input file contains one test case. Each case starts with a line containing numbers (), and , which are the total number of cities, and the number of highways, respectively. Then lines follow, each describes a highway by integers: City1
City2
Cost
Status
where City1
and City2
are the numbers of the cities the highway connects (the cities are numbered from to ), Cost
is the effort taken to repair that highway if necessary, and Status
is either , meaning that highway is destroyed, or , meaning that highway is in use.
Note: It is guaranteed that the whole country was connected before the war.
Output Specification:
For each test case, just print in a line the city we must protest the most, that is, it will take us the maximum effort to rebuild the connection if that city is conquered by the enemy.
In case there is more than one city to be printed, output them in increasing order of the city numbers, separated by one space, but no extra space at the end of the line. In case there is no need to repair any highway at all, simply output .
Sample Input 1:
1 | 4 5 |
Sample Output 1:
1 | 1 2 |
Sample Input 2:
1 | 4 5 |
Sample Output 2:
1 | 0 |
2. 题解
分析
直接暴力枚举,考虑去除每个节点后,对剩余的节点使用 Prim 算法计算生成最小生成树所需要的代价,如果不能生成最小生成树,则代价为无穷 INF
;依据题意可知,只有 destroyed 的高速公路需要修复代价,即 Status = 0
;而 Status = 1
的高速公路不需要修复代价,即修复代价为 。由于 Status = 1
的高速公路修复代价都一样,故对这部分高速公路可以直接使用并查集+数组来合并可以合并的联通集;对于 Status = 0
的高速公路的部分,在前者操作的基础上,使用有序数组(按照 cost 从高到底降序)来进一步生成最小生成树,即并查集+有序数组。由于去除了 Status = 1
,故进行 sort 操作较快。
由于 ,故 ,边 sort 复杂度 ,答案 sort 复杂度 ,枚举所有节点并构建最小生成树 。故最终复杂度为 。由于数据不是很大,故「直接枚举+并查集+Prim」算法也跑的挺快的。
代码
1 |
|