PAT 甲级 1048 Find Coins (25 分)(较简单,开个数组记录一下即可)

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 1 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 (≤, the total number of coins) and M (≤, 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 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

题意:

 假设你有N个货币,面值从1到500不等,只允许使用其中的两枚货币,然后刚好达到付款要求,如果存在多组方案,输出其中一个货币最小的方案。如果没有符合要求的方案,输出No Solution。

题解:

货币的面值只在1~500之间,那么使用一个500的int 数组存储每个面额的张数即可。

采用空间的方法,直接看另一个数是否存在。注意可能存在2个重复的数,所以要计数,而不是用bool表示。

这道题的测试点有个bug,题目明明说的是面值500,但是第三个测试点,给出了面值999的测试,所以数组不能只开500多。

AC代码:

#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<string>
#include<cstring>
using namespace std;
int v[1005];//505会出现段错误
int main(){
    int n,m,x;
    memset(v,0,sizeof(v));
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>x;
        v[x]++;
    }
    int f=0;
    for(int i=1;i<=500;i++){
        if(i!=m-i){
            if(v[i]&&v[m-i]){
                f=1;
                cout<<i<<" "<<m-i;
                break;
            }
        }else if(i==m-i&&v[i]>=2){
                f=1;
                cout<<i<<" "<<m-i;
                break;
        }
    }
    if(!f) cout<<"No Solution";
    return 0;
}
原文地址:https://www.cnblogs.com/caiyishuai/p/11468183.html