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)
  • 相关阅读:
    tar 解压缩命令
    utf8转为gb2312的函数
    .bash_profile和.bashrc的区别(如何设置生效)
    shell脚本操作mysql数据库—创建数据库,在该数据库中创建表(插入,查询,更新,删除操作也可以做)
    CentOS查看系统信息命令和方法
    SSL Programming Tutorial
    高性能、高并发TCP服务器(多线程调用libevent)
    phpmyadmin数据导入最大限制的解决方法
    微信分享网页的缩略图
    微信公众账号添加关注按钮和分享到朋友圈按钮.
  • 原文地址:https://www.cnblogs.com/h-hkai/p/12856631.html
Copyright © 2011-2022 走看看