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 10^​5​​ 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 (≤10​^5​​, the total number of coins) and M (≤10​^3​​, 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 V​1​​ and V​2​​ (separated by a space) such that V​1​​+V​2​​=M and V​1​​≤V​2​​. If such a solution is not unique, output the one with the smallest V​1​​. If there is no solution, output No Solution instead.

Sample Input 1:

8 15
1 2 8 7 2 4 11 15

Sample Output 1:

4 11

Sample Input 2:

7 14
1 8 7 2 4 11 15

Sample Output 2:

No Solution

题目大意

题目中对付款有一个特殊的要求:每张账单,Eva只能使用两个硬币来支付恰好的金额。题目要求告诉她,对于任何给定数额的钱,她是否能找到两个硬币来支付。

解题思路

  1. 采用Hash法记录每种金额的硬币个数;
  2. 从可能的最小值开始查找,判断能否找到两个硬币正好支付费用;
  3. 需要注意的是有可能需要两个同样金额的硬币,则如该面值的硬币只有一枚则不可支付;
  4. 输出结果并返回零值。

代码

#include<stdio.h>
int hash[510];
int main(){
    int N,M;
    int i,a;
    scanf("%d%d",&N,&M);
    for(i=0;i<N;i++){
        scanf("%d",&a);
        hash[a]++;
    }
    i=(M-500)>0?(M-500):0;
    for(;i<=500;i++){
        if((hash[i]--)&&hash[M-i]){
            printf("%d %d\n",i,M-i);
            break;
        }else{
            hash[i]++;
        }
    }
    if(i>500){
        printf("No Solution\n");
    }
    return 0;
} 

运行结果

PAT-A1048 Find Coins 题目内容及题解

 

相关文章:

  • 2021-08-24
  • 2021-09-26
  • 2021-07-02
  • 2021-04-25
  • 2022-01-12
  • 2021-09-16
  • 2021-07-20
  • 2021-08-18
猜你喜欢
  • 2021-04-04
  • 2021-06-12
  • 2022-12-23
  • 2021-05-31
  • 2021-05-11
  • 2022-01-07
  • 2021-07-13
相关资源
相似解决方案