• 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)
  • 相关阅读:
    JavaScript监听、设置全部ajax访问属性获取返回值(状态码)
    如何在Vue项目中使用vw实现移动端适配
    git 常用命令金字教程
    移动web开发之像素和DPR详解
    小程序-微信开发者工具使用
    小程序开发框架:Taro(一)基础篇
    vscode代码自动补全失效
    JS、C#编码解码
    PHP网页缓存技术
    ajaxfileupload回到json带<pre>
  • 原文地址:https://www.cnblogs.com/h-hkai/p/12856631.html
Copyright © 2020-2023  润新知