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;
    }
    
  • 相关阅读:
    080630 東京 曇り
    快速切题 sgu123. The sum
    快速切题 sgu119. Magic Pairs
    快速切题 sgu118. Digital Root 秦九韶公式
    SGU 124. Broken line 射线法 eps的精准运用,计算几何 难度:3
    快速切题 sgu120. Archipelago 计算几何
    sgu 121. Bridges painting 列举情况 难度:1
    快速切题sgu126. Boxes
    快速切题sgu127. Telephone directory
    sgu 122. The book 满足ore性质的汉密尔顿回路 难度:2
  • 原文地址:https://www.cnblogs.com/musecho/p/12290649.html
Copyright © 2011-2022 走看看