[TOC]
题目描述
注:你可以在Acwing找到蓝书所有例题的中文体面,该英文题面可以在牛客竞赛OJ尝试提交
The Contortion Brothers are a famous set of circus clowns, known worldwide for their incredible ability to cram an unlimited number of themselves into even the smallest vehicle. During the off-season, the brothers like to get together for an Annual Contortionists Meeting at a local park. However, the brothers are not only tight with regard to cramped quarters, but with money as well, so they try to find the way to get everyone to the party which minimizes the number of miles put on everyone’s cars (thus saving gas, wear and tear, etc.). To this end they are willing to cram themselves into as few cars as necessary to minimize the total number of miles put on all their cars together. This often results in many brothers driving to one brother’s house, leaving all but one car there and piling into the remaining one. There is a constraint at the park, however: the parking lot at the picnic site can only hold a limited number of cars, so that must be factored into the overall miserly calculation. Also, due to an entrance fee to the park, once any brother’s car arrives at the park it is there to stay; he will not drop off his passengers and then leave to pick up other brothers. Now for your average circus clan, solving this problem is a challenge, so it is left to you to write a program to solve their milage minimization problem.
输入描述:
1 | Input will consist of one problem instance. The first line will contain a single integer n indicating the number of highway connections between brothers or between brothers and the park. The next n lines will contain one connection per line, of the form name1 name2 dist, where name1 and name2 are either the names of two brothers or the word Park and a brother's name (in either order), and dist is the integer distance between them. These roads will all be 2-way roads, and dist will always be positive.The maximum number of brothers will be 20 and the maximumlength of any name will be 10 characters.Following these n lines will be one final line containing an integer s which specifies the number of cars which can fit in the parking lot of the picnic site. You may assume that there is a path from every brother's house to the park and that a solution exists for each problem instance. |
输出描述:
1 | Output should consist of one line of the form |
示例1
输入
复制;)
1 | 10 |
输出
复制;)
1 | Total miles driven: 183 |
题目分析:
大致题意是给你一个n个点,m条边的无向图,求出无向图的一课最小生成树,满足1号节点的度数不超过S。两种做法:
1、先求出最小生成树,1号节点度数如果超过S就循环 degree[1] - S 次,每次循环断掉一条与1连接的边,加上一条断掉的连通块与包含1的连通块的边使增加的权重最小。
2、一开始把1号节点先拿掉,那么整个图就分成了诺干个连通块,所以我们只需要对每个连通块求一边MST,再把每个连通块与1连一条权值最小的边。
对第二种方法分类讨论一下
若S<T:
那么我们必然就是无解情况.
若S=T
那么此时我们的生成树,就是我们的最小生成树.
若S>T
此时1的度数小于S,我们还可以通过修改边继续优化答案:枚举1的所有出边,如果(1,x) 边权为 z 还未在MST中,则我们可以找到从 x 到 1 的路径上最长的边(在MST中的边)边权为 w 如果 w - z > 0则我们可以用(1,x)替换这条边使答案优化(w-z)。重复循环(S-degree[1])次或 w-z <= 0.详细实现见代码。
PS: 这道题思路花了十几分钟想出来的,代码调试了几个小时,太锻炼码力了…….
python code:
1 | import sys |