Hash table application example

Example:
Eva likes to collect coins from the entire universe.
One day, she went to a universe shopping mall to shop, and she could use various coins to pay at the checkout.
However, there is a special payment requirement: for each bill, she can only use exactly two coins to pay the consumption amount accurately.
Given the denominations of all the coins she has, please help her determine whether she can find two coins to pay for the given amount.

The first line of the input format
contains two integers N and M, which represent the number of coins and the amount to be paid respectively.
The second line contains N integers, representing the denomination of each coin.

The output format
outputs one line, containing two integers V1, V2, representing the denominations of the two selected coins, such that V1≤V2 and V1+V2=M.
If the answer is not unique, the solution with the smallest V1 is output.
If there is no solution, output No Solution.

Data range
1≤N≤105,
1≤M≤1000 The

codes are as follows:

#include <iostream>
#include <unordered_set>
#include <cstring>
using namespace std;
const int MAX = 10010;

int main()
{
    
    
    int n,m;
    cin>>n>>m;
    unordered_set<int> hash;
    int v1 = MAX,v2;
    for (int i = 0;i<n;i++)
    {
    
    
        int a,b;
        cin>>a;
        b = m-a;
        if (hash.count(b))
        {
    
    
            hash.insert(a);
            if (a > b) swap(a,b);
            if (a < v1) v1 = a,v2 = b;
        }
        else
        {
    
    
            hash.insert(a);
        }
        
    }
    if(v1!=MAX)
    cout<<v1<<" "<<v2<<endl;
    else
    {
    
    
        cout<<"No Solution"<<endl;
    }
    
    
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_51955470/article/details/113995113