PAT_A 1048. Find Coins (25)

来源:互联网 发布:有道云笔记数据恢复 编辑:程序博客网 时间:2024/06/04 19:32

1048. Find Coins (25)

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 couldonly use exactly two coins to pay the exact amount. Since she has as many as 105 coins withher, she definitely needs your help. You are supposed to tell her, for any given amount ofmoney, 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 topay). 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 withthe smallest V1. If there is no solution, output "No Solution" instead.Sample Input 1:8 151 2 8 7 2 4 11 15Sample Output 1:4 11Sample Input 2:7 141 8 7 2 4 11 15Sample Output 2:No Solution
  • 分析:

    • 题目:从一堆硬币中找到两个面值为a,b付钱M,M=a+b,若果存在多种情况,输出a最小的。
    • 解题:用一个数组记录硬币存在,排序后,顺序遍历,判断M-a是否存在,若存在则找到,当然需要判断a=b是,a,b是不是同一个数,若M-a<0则失败
  • code:

#include<iostream>#include<vector>#include<cstdio>#include<algorithm>using namespace std;vector<int> coins;int exist[100010];int main(){    freopen("in","r",stdin);    fill_n(exist,100010,0);    int N,M,tmp;    scanf("%d%d",&N,&M);    for(int i=0;i<N;i++)    {        scanf("%d",&tmp);        exist[tmp]++;        coins.push_back(tmp);    }    sort(coins.begin(),coins.end());    bool find=false;    int i=0;    for(i=0;i<N;i++)    {        tmp=M-coins[i];//做差,若存在,且不是它自己则成功        if(tmp>0&&exist[tmp])        {            if(tmp+tmp==M&&exist[tmp]==1)              find=false;            else              find=true;            break;        }else if(tmp<=0)        {            find=false;            break;        }    }    if(find)        printf("%d %d\n",coins[i],tmp);    else        printf("No Solution\n");    return 0;}
  • AC
    pat_1048
原创粉丝点击