zoukankan      html  css  js  c++  java
  • 【PAT甲级】1048 Find Coins (25分):哈希

    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 could only use exactly two coins to pay the exact amount. Since she has as many as 105 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 (≤105, the total number of coins) and M (≤103, 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 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 with the smallest V1. 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
    

    分析:哈希

    先遍历数字序列,数字本身作为数组Time的下标,记录数字出现次数。从i=0开始遍历到M/2+1,查找该数字i和M-i是否都出现了,出现则结束,保证了i<=M-i且有多个结果时输出最小的i。


    代码

    #include<iostream>
    
    using namespace std;
    
    const int maxM=1010;
    int Time[maxM];//数组:硬币出现次数
    int main() {
    	fill(Time,Time+maxM,0);
    	int N,M;
    	int coin;
    
    	scanf("%d%d",&N,&M);
    	for(int i=0; i<N; i++) {
    		scanf("%d",&coin);
    		Time[coin]++;
    	}
    
    	for(int i=0; i<M/2+1; i++) {
    		if(Time[i]) {//不等于0
    			Time[i]--;
    			if(Time[M-i]) {
    				printf("%d %d",i,M-i);
    				return 0;
    			}
    			Time[i]++;
    		}
    	}
    	printf("No Solution");
    
    	return 0;
    }
    
  • 相关阅读:
    //设N是一个四位数,它的9倍恰好是其反序数(例如:1234 的反序数是4321),求N的值。
    安装oracle后,电脑变卡变慢的解决办法
    JSONP
    vue-resource发起get、post、jsonp请求
    Vue实例的生命周期
    自定义全局指令让文本框获取焦点
    自定义全局按键修饰符
    es2017 提供的针对字符串填充的函数:padStart、padEnd
    自定义私有过滤器
    fiddler教程
  • 原文地址:https://www.cnblogs.com/musecho/p/12290649.html
Copyright © 2011-2022 走看看