PAT----甲级 1048. Find Coins (25)

1048. Find Coins (25)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 105 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 (<=105, the total number of coins) and M(<=103, 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

这道题如果用暴力解的话会超时,所以可以考虑一下用hash数组的方法来解决这个问题

hash(哈希表) 思路很简单,就是输入一串字符或者数字,用数组存起来,并将其进行标记。在查找时,直接通过数组下标的直接获得该字符串或者数字是否出现过。  当然也可以用来计算该字符出现了几次

#include <bits/stdc++.h>

using namespace std;

int num[100100] = {0};
int used[100100] = {0};
int main()
{
    int n,m;
    cin>>n>>m;
    int x;
    for(int i=0; i<n; i++)
    {
        cin>>x;
        num[x] = 1;                     ///have
        used[x] ++;                ///这里使用++操作是因为题中没有说每个价值的硬币只出现一次
    }
    int res = 0;
    bool flag = false;
    for(int i=0; i<100100; i++)
    {
        if(num[i] != 0)
        {
            res = m-i;
            used[i]--;
            if(num[res] !=0 && used[res] !=0)
            {
                flag = true;
                x = i;
                break;
            }
            used[i] ++;
        }
    }
    if(flag)
        cout<<x<<" "<<res<<endl;
    else
        cout<<"No Solution"<<endl;
}



猜你喜欢

转载自blog.csdn.net/qq_38851184/article/details/80159788