hash

哈希表是根据设定的哈希函数和处理冲突的方法将一组关键字映射到一个有限的地址空间上;


hduoj1264

counting squares:计算unit,以一个rect[101][101]的数组存放是否数过的标记;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//暴力:
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

using namespace std;

int rect[110][110];

int main()
{
int ax,ay,bx,by;
int res=0;
memset(rect,0,sizeof(rect));
while(scanf("%d%d%d%d",&ax,&ay,&bx,&by)!=EOF){
if(ax<0){
cout<<res<<endl;
if(ax==-2)break;//结束
memset(rect,0,sizeof(rect));
res=0;
}
//还在输入
if(ax>bx)swap(ax,bx);
if(ay>by)swap(ay,by);
for(int i=ax;i<bx;i++){
for(int j=ay;j<by;j++){
if(rect[i][j]==0){
res++;
rect[i][j]=1;
}
}
}
}
return 0;
}

hduoj1280

将in中两两相加的nX(n-1)/2个值,映射到sum数组中(和作为sum的下标值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//哈希:
#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;
int in[3001];
int sum[10001];
//将in中两两相加的n*(n-1)/2个值,映射到sum数组中

int main()
{
//使用暴力法的话
//3000个整数不管在时间上还是空间上都不ok
//选择hash
int n,m;
while(scanf("%d%d",&n,&m)!=EOF){
memset(in,0,sizeof(in));
memset(sum,0,sizeof(sum));
for(int i=0;i<n;i++)scanf("%d",&in[i]);
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
sum[in[i]+in[j]]++;
}
}
//在sum数组中找到前m大的数
int tmp=10000;
bool flag=false;
while(tmp>=0&&m>0){
if(sum[tmp]==0){
tmp--;
continue;
}
if(flag){
cout<<" "<<tmp;
}
else cout<<tmp;
flag=true;
sum[tmp]--;
m--;
}
cout<<endl;
}
return 0;
}