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)
  • 相关阅读:
    Permutations II
    LeetCode Sudoku Solver
    LeetCode Insert Interval
    LeetCode Unique Binary Search Trees II
    LeetCode Edit Distance
    LeetCode N-Queens II
    ListView自定义适配器--10.17
    Android开发--ListPreferance 运行报错:android.preference.ListPreference.findIndexOfValue(ListPreference.java:169)
    使用Genymotion作Android开发模拟器:安装Genymotion、部署Genymotion Vitrue Device、安装Genymotion eclipse插件
    Android ADB server didn't ACK * failed to start daemon * 简单有效的解决方案
  • 原文地址:https://www.cnblogs.com/h-hkai/p/12856631.html
Copyright © 2011-2022 走看看