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;
    }
    
  • 相关阅读:
    fatal error C1071: unexpected end of file found in comment
    error: reference to 'max' is ambiguous
    STL list链表的用法详解
    头文件
    error C4430: missing type specifier
    python selenium-2 定位元素
    selenium page object模式
    selenium进阶
    导入testng管理测试用例
    selenium java-3 定位元素的八种方法
  • 原文地址:https://www.cnblogs.com/musecho/p/12290649.html
Copyright © 2011-2022 走看看