cjweffort

博客园 首页 联系 订阅 管理

two points

don't used hash table

#include <cstdio>
#include <algorithm>
using namespace std;

const int INF=0x7fffffff;
const int N=100003;
int coin[N];
int n,needSum;

void findCoins(){
	int i=0,j=n-1;
	int lowMinCoin=INF,left=-1,right=-1;
	while(i<j){
		if(coin[i]+coin[j]==needSum){
			if(coin[i]<lowMinCoin){
				left=coin[i];
				right=coin[j];
				lowMinCoin=coin[i];
			}
			i++,j--;
		}
		else if(coin[i]+coin[j]>needSum)
			j--;
		else
			i++;
	}
	if(left==-1&&right==-1)
		printf("No Solution\n");
	else
		printf("%d %d\n",left,right);
}

int main()
{
	scanf("%d%d",&n,&needSum);
	for(int i=0;i<n;i++)
		scanf("%d",coin+i);
	sort(coin,coin+n);
	findCoins();
    return 0;
}

use hash table

#include <cstdio>
#include <cstring>

const int INF=501;
const int N=503;
int hash[N];
int n,needSum;

void findCoins(){
	int i=1,j=500;
	int lowMinCoin=INF,left=-1,right=-1;
	while(i<=j){
		if(i==j){
			if(hash[i]<2)
				break;
		}
		if(hash[i]>0){
			if(hash[j]>0){
				if(i+j==needSum){
					if(i<lowMinCoin)
						left=i,right=j,lowMinCoin=i;
					i++,j--;
				}
				else if(i+j>needSum)
					j--;
				else
					i++;
			}
			else
				j--;
		}
		else
			i++;
	}
	if(left==-1&&right==-1)
		printf("No Solution\n");
	else
		printf("%d %d\n",left,right);
}

int main()
{
	memset(hash,0,sizeof(hash));
	scanf("%d%d",&n,&needSum);
	for(int i=0;i<n;i++){
		int temp;
		scanf("%d",&temp);
		hash[temp]++;
	}
	findCoins();
	return 0;
}


posted on 2013-03-12 11:26  cjweffort  阅读(170)  评论(0编辑  收藏  举报