zoukankan      html  css  js  c++  java
  • A1048. Find Coins

    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

     1 #include<cstdio>
     2 using namespace std;
     3 const int N = 1005;
     4 int hashTB[N] = {0, 0};
     5 int main(){
     6     int n, m, v;
     7     scanf("%d %d", &n, &m);
     8     for(int i = 0; i < n; i++){
     9         scanf("%d", &v);
    10         hashTB[v]++;
    11     }
    12     for(int i = 0; i < N; i++){
    13         if(hashTB[i] && hashTB[m - i]){
    14             if(i == m - i && hashTB[i] <= 1){
    15                 continue;
    16             }
    17             printf("%d %d
    ", i, m - i);
    18             return 0;
    19         }
    20     }
    21     printf("No Solution
    ");
    22     return 0;
    23 }
    View Code

    总结:

    1、本题题意:给出拥有的硬币,给出要凑出的面额M,找出两个硬币且他们的和为M。显然暴力法很可能超时,所以关键是要想到用哈希表。

    2、由于每个钱的面额都小于500,但M可能大于500,故hashTB的大小最好为1000,否则用指针i遍历时,M - i可能越界。

    3、此题还可以用二分法。先对所有面值进行排序,遍历a[0]、a[1]……,对于每一个a[i],寻找是否存在M - a[ i ]且 M - a[i] 不是a[i],若找到则输出。

  • 相关阅读:
    python-Python调用wcf接口
    一个数据驱动的ui自动化框架思路
    selenium分布式部署
    UI自动化-Element is not clickable at point-----问题记录
    idea下载git代码
    windows的hosts文件路径
    端口号
    Hadoop压缩
    MongoDB(单节点)环境配置
    快排
  • 原文地址:https://www.cnblogs.com/zhuqiwei-blog/p/8496217.html
Copyright © 2011-2022 走看看