1048. Find Coins (25)

来源:互联网 发布:rtl8710编程方法 编辑:程序博客网 时间:2024/05/17 02:59

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:
8 151 2 8 7 2 4 11 15
Sample Output 1:
4 11
Sample Input 2:
7 141 8 7 2 4 11 15
Sample Output 2:

No Solution

分析

(1)一看到搜索输入之间关系的,便想到用2次循环必然超时,必然要hash。

(2)因为结果要求从输出最小的,也是为了之后的方便,先快排了下。

(3)题中N给的要比M大的多,根据题意思,比M值大的硬币就可以考虑直接放弃不HASH了。

(4)比较hash值的时候,一般是两个都大于0即可,如果刚好需要两个一样的硬币,那那个值就得大于1了。

(5)中间又一次混淆了i和coin[i],真的是够了。。

#include<cstdio>#include<algorithm>using namespace std;bool cmp (int p, int q){return p<q;}int main (){int n,m,i;scanf ("%d%d",&n,&m);int coin[100010],hash[1010]={0};for (i=0;i<n;i++){scanf("%d",&coin[i]);}sort (coin,coin+n,cmp);    for (i=0;i<n;i++){if (coin[i]<m)hash[coin[i]]++;}int flag=0;//for (i=0;coin[i]<m;i++){//printf("%d %d\n",coin[i],hash[coin[i]]);//}for (i=0;coin[i]<m;i++){if (m-coin[i]!=coin[i]){if (hash[coin[i]]!=0&&hash[m-coin[i]]!=0){flag=1;break;}}else {if (hash[coin[i]]>=2){flag=1;break;}}}if (flag==1) printf ("%d %d",coin[i],m-coin[i]);else printf ("No Solution");//return 0;}



0 0
原创粉丝点击