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;
}