Fiber Communications
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 3804 | Accepted: 1160 |
Description
Farmer John wants to connect his N (1 <= N <= 1,000) barns (numbered 1..N) with a new fiber-optic network. However, the barns are located in a circle around the edge of a large pond, so he can only connect pairs of adjacent barns. The circular configuration means that barn N is adjacent to barn 1.
FJ doesn't need to connect all the barns, though, since only certain pairs of cows wish to communicate with each other. He wants to construct as few
connections as possible while still enabling all of these pairs to communicate through the network. Given the list of barns that wish to communicate with each other, determine the minimum number of lines that must be laid. To communicate from barn 1 to barn 3, lines must be laid from barn 1 to barn 2 and also from barn 2 to barn 3(or just from barn 3 to 1,if n=3).
FJ doesn't need to connect all the barns, though, since only certain pairs of cows wish to communicate with each other. He wants to construct as few
connections as possible while still enabling all of these pairs to communicate through the network. Given the list of barns that wish to communicate with each other, determine the minimum number of lines that must be laid. To communicate from barn 1 to barn 3, lines must be laid from barn 1 to barn 2 and also from barn 2 to barn 3(or just from barn 3 to 1,if n=3).
Input
* Line 1: Two integers, N and P (the number of communication pairs, 1 <= P <= 10,000)
* Lines 2..P+1: two integers describing a pair of barns between which communication is desired. No pair is duplicated in the list.
* Lines 2..P+1: two integers describing a pair of barns between which communication is desired. No pair is duplicated in the list.
Output
One line with a single integer which is the minimum number of direct connections FJ needs to make.
Sample Input
5 2 1 3 4 5
Sample Output
3
Hint
[Which connect barn pairs 1-2, 2-3, and 4-5.]
Source
题意:就是有n个数排成一个圈,刚开始都没有边相连,你可以给它们之间加上边,但能给相邻的数字之间加边,给出几对询问,要求这几对询问的2个点都必须相连,求最少的需要添加的边数
分析:可以从结果思考,最后的结果一定会是几条链(如果是一个圈的话,那么任意去掉一条边绝对可以满足条件且边数更少),于是就可以枚举圈的断点,从而确定连接关系统计一下就行。不过这里表达连接关系时,有点技巧,就是用f[i]=j表示i..j都相连,从而就可以迅速维护了。
不过这里说一下本渣对本题的误解:
误认为要一次性枚举所有断点的位置,从而变成不可完成的复杂度:这里其实只要每次枚举一个断点,一共枚举n次就行了,因为每个询问都只有2个决策,要么顺时针要么逆时针,确定一个断点后就一定可以知道次询问的添边方向,而且可以发现这样做完剩下的就是那些没用的断点。