Elegant Construction
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=5813
Description
Being an ACMer requires knowledge in many fields, because problems in this contest may use physics, biology, and even musicology as background. And now in this problem, you are being a city architect! A city with N towns (numbered 1 through N) is under construction. You, the architect, are being responsible for designing how these towns are connected by one-way roads. Each road connects two towns, and passengers can travel through in one direction. For business purpose, the connectivity between towns has some requirements. You are given N non-negative integers a1 .. aN. For 1 <= i <= N, passenger start from town i, should be able to reach exactly ai towns (directly or indirectly, not include i itself). To prevent confusion on the trip, every road should be different, and cycles (one can travel through several roads and back to the starting point) should not exist. Your task is constructing such a city. Now it's your showtime!Input
The first line is an integer T (T <= 10), indicating the number of test case. Each test case begins with an integer N (1 <= N <= 1000), indicating the number of towns. Then N numbers in a line, the ith number ai (0 <= ai < N) has been described above.Output
For each test case, output "Case #X: Y" in a line (without quotes), where X is the case number starting from 1, and Y is "Yes" if you can construct successfully or "No" if it's impossible to reach the requirements. If Y is "Yes", output an integer M in a line, indicating the number of roads. Then M lines follow, each line contains two integers u and v (1 <= u, v <= N), separated with one single space, indicating a road direct from town u to town v. If there are multiple possible solutions, print any of them.Sample Input
3 3 2 1 0 2 1 1 4 3 1 1 0Sample Output
Case #1: Yes 2 1 2 2 3 Case #2: No Case #3: Yes 4 1 2 1 3 2 4 3 4Source
2016 Multi-University Training Contest 7##题意: 要求构造一个有向图,使得点i能够恰好到达Ai个点.(直接间接皆可) 输出任意满足条件的图即可,没有要求最小.
##题解: 由于没有要求边数最小,所以直接排序再贪心就可以了. 先将Ai数组按升序排列. 由于后面要输出端点,所以先记录下各点排序前的序号. 首先对于 Ai = 0 的情况,肯定要位于某个末端. (若没有Ai=0,则肯定会存在环) 对于Ai = m, 要在它之前找恰好m个点跟它联通, 贪心的取法是: 先跟在这之前的所有Ai = 0的点都连一条边,再跟Ai = 1的点都连边,依此类推直到连够m个点. 这样以来就避免了连边时的重复情况,使得每次连边都恰好使得联通点的个数增加一. 所以只需要判断 Ai=m 之前是否有至少m个点即可.
官方题解: 将顶点按能到达的点数从小到大排序,排好序之后每个点只能往前面的点连边. 因而如果存在一个排在第i位的点,要求到达的点数大于i-1,则不可行;否则就可以按照上述方法构造出图. 复杂度O(N^2).
##代码: ``` cpp #include