程序设计基础1 散列法A1048

1048 Find Coins (25)(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 10^5^ 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 (<=10^5^, the total number of coins) and M(<=10^3^, 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.

一,我的解法

思路:从原因出发,都加加看,加的结果存在散列里,若在散列里找到m,就正确,否则错误。

缺点:时间复杂度为n^2,运行超时。

#include<iostream>
#include<algorithm>
using namespace std;
int coins[100100];
bool amount[3010];
int main(){
	int n,m;
	int a,b;
	scanf("%d %d",&n,&m);
	for(int i=0;i<n;i++){
		scanf("%d",&coins[i]);
	}
	sort(coins,coins+n);
	for(int i=0;i<n;i++){
		a=coins[i];
		int flag = 0;
		for(int j=i+1;j<n;j++){
			b=coins[j];
			if(a+coins[n-1]>1000)
				continue;
			if(a+b==m){
				amount[a+b]=true;
				printf("%d %d",a,b);
				flag = 1;
			}
			else if(a+b<=1000){
				amount[a+b]=true;
			}
		}
		if(flag==1){
			break;
		}
	}
	if(amount[m]==false)
		printf("No Solution");
	return 0;
}

二,正确散列

思路:从结果出发,散列表存储输入的数据,并且还能知道输入形同的数据的个数。for循环里只需要判断i从1开始,i和m-i是否都存在散列表中即可。时间复杂度仅为o(m)

#include<iostream>
#include<algorithm>
using namespace std;
int amount[1010]={0};
int main(){
	int m,n,a;
	scanf("%d %d",&n,&m);
	for(int i=0;i<n;i++){
		scanf("%d",&a);
		++amount[a];
	}
	for(int i=1;i<m;i++){
		if(amount[i]&&amount[m-i]){
			if(i==m-i&&amount[i]<=1)
				continue;
			printf("%d %d",i,m-i);
			return 0;
		}
	}
	printf("No Solution");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq2285580599/article/details/81071478
今日推荐