zoukankan      html  css  js  c++  java
  • 1048 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 1 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 (≤, the total number of coins) and M (≤, 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 V​1​​ and V​2​​ (separated by a space) such that V​1​​+V​2​​=M and V​1​​≤V​2​​. If such a solution is not unique, output the one with the smallest V​1​​. 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

    题意:

      给出一个数组在这个数组中找出两个数,使其相加为m。

    思路:

      将数组排序,从数组的两头开始向中间收缩,直到两数相加等于m。

    Code:

     1 #include <bits/stdc++.h>
     2 
     3 using namespace std;
     4 
     5 int main() {
     6     int n, m;
     7     cin >> n >> m;
     8     vector<int> coins(n);
     9     for (int i = 0; i < n; ++i) cin >> coins[i];
    10     sort(coins.begin(), coins.end());
    11     int i = 0, j = coins.size() - 1;
    12     while (i < j) {
    13         if (coins[i] + coins[j] > m)
    14             j--;
    15         else if (coins[i] + coins[j] < m)
    16             i++;
    17         else
    18             break;
    19     }
    20     if (i >= j)
    21         cout << "No Solution" << endl;
    22     else
    23         cout << coins[i] << " " << coins[j] << endl;
    24     return 0;
    25 }
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    鼠标事件大全
    jpa仓库接口
    mysql从一个表中拷贝数据到另一个表中sql语句
    mybatis中为sql中传值#{}和${}的区别
    @Autowired与@Resource的区别
    sping配置文件中引入properties文件方式
    Mybatis中实体类中的字段跟对应表的字段不一致时解决办法
    eclispe输入@注解时提示所有注解的设置
    eclipse中如何设置tomcat启动时间
    log4j的使用
  • 原文地址:https://www.cnblogs.com/h-hkai/p/12856631.html
Copyright © 2011-2022 走看看