PAT甲级1048 Find Coins (25分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

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

二、解题思路

还算是一道蛮简单的题目,代码也非常简单。题目大意是,给出要凑出来的总金额以及手上现有的面额,求出用哪两枚金币可以凑出来题目给的数字。我们可以将手上现有的面额从小到大进行排序,随后用cnt数组表示对应面额金币的数目,若对应数字为0,则说明手上没有这种面额的金币。遍历所有手上有的面额,查看与它相加得M的数字存不存在,如果存在,直接输出,return,不存在则继续。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 1010;
int cnt[maxn] = {
    
    0};
int main()
{
    
    
  int N, M, tmp;
  vector<int> all;
  scanf("%d%d", &N, &M);
  for(int i=0; i<N; i++)
  {
    
    
	scanf("%d", &tmp);
    all.push_back(tmp);
    cnt[tmp]++;
  }
  sort(all.begin(), all.end());
  for(int i=0; i<N; i++)
  {
    
    
    cnt[all[i]]--;
    if(all[i] < M  && cnt[M-all[i]] > 0)
    {
    
    
      printf("%d %d\n", all[i], M-all[i]);
      return 0;
    }
  }
  printf("No Solution\n");
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108593068