PAT 1048 Find Coins (25)

题目要求

Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she could only use exactly two coins to pay the exact amount. Since she has as many as 105 coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find two coins to pay for it.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (<=105, the total number of coins) and M(<=103, the amount of money Eva has to pay). The second line contains N face values of the coins, which are all positive numbers no more than 500. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the two face values V1 and V2 (separated by a space) such that V1 + V2 = M and V1 <= V2. If such a solution is not unique, output the one with the smallest V1. If there is no solution, output “No Solution” instead.

Sample Input 1:

1
2
8 15
1 2 8 7 2 4 11 15

Sample Output 1:

1
4 11

Sample Input 2:

1
2
7 14
1 8 7 2 4 11 15

Sample Output 2:

1
No Solution

解题思路

读完题目之后,首先想到的解法就是先对整个的coin数组进行排序,然后开始遍历整个数组,以当前元素为V1,与后面的元素相加,比较与M的大小,直到找到第一个结果。这样做的时间复杂度是O(N^2),但是看到题目的时间要求是50ms,我就觉得应该会卡时间,直接用O(n^2)的算法肯定会超时。

接着,我就想到前几天看网上1044的题解的时候,有人用来降低复杂度的方法是二分法,而这道题用二分法也非常合适!所以只保留之前的外循环,内层循环使用二分法实现,最终一遍通过!

代码

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
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
int coins[100000 + 10];
int m;
int main()
{
int n;
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++)
{
scanf("%d", coins + i);
}
sort(coins, coins + n);
int start, end, mid;
for (int i = 0; i < n - 1; i++)
{
start = i + 1;
end = n - 1;
mid = (start + end) / 2;
while (coins[i] + coins[mid] != m && end >= start && start >= i + 1 && end <= n - 1)
{
if (coins[i] + coins[mid] < m)
{
start = mid + 1;
mid = (start + end) / 2;
}
else
{
end = mid - 1;
mid = (start + end) / 2;
}
}
if (coins[i] + coins[mid] == m && mid > i && mid < n)
{
printf("%d %d\n", coins[i], coins[mid]);
system("pause");
return 0;
}
}
printf("No Solution\n");
system("pause");
return 0;
}