Question 197.pat Grade A Exercise - 1048 Find Coins (25 points)


Question 197.pat Grade A Exercise - 1048 Find Coins (25 points)


1. The topic

insert image description here
insert image description here

2. Problem solving

This question asks you to find two coins from a pile of coins that can make up the money you want, which can be directly converted into the value of one coin, to see if the money you want to make up - the value of this coin exists, directly Just use hash thinking. code show as below:

#include <bits/stdc++.h>

using namespace std;

int value[2001];//开大点应对M很大的情况,不然会段错误,因为下面要访问value[v2],v2=M-i可能会超范围

int main()
{
    
    
    int N,M;
    cin>>N>>M;
    for(int i=0;i<N;i++)
    {
    
    
        int input;
        scanf("%d",&input);
        value[input]++;//直接哈希思想,用于标记这个下标对应coin的个数,刚好下标表示面值也省的排序了
    }
    int i;
    for(i=1;M-i>=i;i++)
    {
    
    
        if(value[i])
        {
    
    
            int v1=i;
            int v2=M-v1;
            value[i]--;
            if(value[v2])//直接用O(1)时间找到面值是否存在
            {
    
    
                printf("%d %d",v1,v2);
                break;
            }
        }
    }
    if(M-i<i)
    {
    
    
        printf("No Solution");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324347538&siteId=291194637