PAT Grade A 1048 Find Coins (25 points)|C++ implementation

1. Title description

Original title link
Insert picture description here

Input Specification:

Insert picture description here

​​Output Specification:

Insert picture description here

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

Two, problem-solving ideas

It's quite a simple subject, and the code is very simple. The main idea of ​​the question is, given the total amount to be collected and the denomination currently in hand, find out which two gold coins can be used to collect the number given in the question. We can sort the current denominations from small to large, and then use the cnt array to represent the number of gold coins of corresponding denominations. If the corresponding number is 0, it means that there are no gold coins of this denomination on hand. Traverse all the denominations on hand, check whether the number of M added to it exists or not, if it exists, output it directly, return, if it does not exist, continue.

Three, AC code

#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;
}

Guess you like

Origin blog.csdn.net/weixin_42393947/article/details/108593068