【王道机试笔记03】Hash的应用

Hash的应用

例2.5 统计同成绩学生人数

代码 2.8
#include<iostream>
using namespace std;
int main(){
	int n,a;
	while(cin >> n){
		if(n == 0)
			break;
		int Hash[105] = {0};
		while(n--){
			cin >> a;
			Hash[a]++;
		}
		cin >> a;
		cout << Hash[a] << endl;
	}
	return 0;
}

例2.6 Sort

代码2.9

由于待排序数字的数量十分庞大(1000000),即使使用时间复杂度为 O(nlogn)的快速排序,其时间复杂度也会达到千万数量级。
由于输入数量的有限性,因此使用Hash列表来纪录是否出现输入数据。

#include<iostream>
using namespace std;
int main(){
	int n,m,x,i;
	while(cin >> n >> m){
		int Hash[1000001] = {0};
		while(n--){
			cin >> x;
			Hash[x+500000] = 1;
		}
		for(i=1000000;i>=0;i--){
			if(m == 0)
				break;
			if(Hash[i] == 1){
				cout << i - 500000 << " ";
				m--;
			}
		}
		cout << endl;
	}
	return 0;
}

谁是你的潜在朋友?

#include<iostream>
using namespace std;
int main(){
	int N,M,i;
	while(cin >> N >> M){
		int P[205] = {0};
		int Hash[205] = {0};
		for(i=0;i<N;i++){
			cin >> P[i];
			Hash[P[i]]++;
		}
		for(i=0;i<N;i++){
			if(Hash[P[i]] > 1)
				cout << Hash[P[i]] - 1 << endl;
			else
				cout << "BeiJu" << endl;
		}
	} 
	return 0;
}

剩下的树

#include<iostream>
using namespace std;
int main(){
	int L,M,i;
	int begin,end;
	while(cin >> L >> M){
		int all = 0;
		int Hash[10005] = {0};
		while(M--){
			cin >> begin >> end;
			for(i=begin;i<=end;i++){
				Hash[i]--;
			}
		}
		for(i=0;i<=L;i++){
			if(Hash[i] == 0)
				all++;
		}
		cout << all << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值