由于学校的工作,我制作了一个hasharray程序,但由于运行速度不够快,我遇到了麻烦。它应该在300毫秒内运行学校测试,而我的时间介于320到900毫秒之间。我已经尝试了一些方法,最可行的方法是实现一个动态数组,例如** hashArray。我这样做很麻烦,所以我要寻求优化代码的一般帮助,或者如何使用动态双精度数组来实现它。
#include <stdlib.h>
#include <stdio.h>
#define ARR_SIZE 44
int hashArray[ARR_SIZE][ARR_SIZE];
int hashKey(int data) { //i create a hash key here, must be smaller than array max size
while (data > ARR_SIZE) {
data %= ARR_SIZE;
}
return data;
}
// vrati 1 ak 's' je podmnozina 't', inak vrati 0.
int is_subset(int s[], int ns, int t[], int nt) {
int j = 0;
for (int i = 0; i < nt; i++) { //here i load numbers from the first array i get from input (the main set)
if (hashArray[hashKey(t[i])] != NULL) {
for (int j = 0; j < ARR_SIZE; j++) {
if (hashArray[hashKey(t[i])][j] == NULL) {
hashArray[hashKey(t[i])][j] = t[i];
break;
}
}
}
}
for (int i = 0; i < ns; i++) { //and here i am comparing elemnts based on hashKey, if this array is a potential subset array of the previous one
for (j = 0; j < ARR_SIZE; j++) {
if (hashArray[hashKey(s[i])][j] == s[i])
break;
if (hashArray[hashKey(s[i])][j+1] != NULL)
continue;
else {
memset(hashArray, 0, sizeof(hashArray));
return NULL;
}
}
}
memset(hashArray, 0, sizeof(hashArray));
return 1;
}
// showcase test
int main(void) {
int i, a[44], na, b[44], nb;
scanf("%d", &na);
for (i = 0; i < na; i++)
scanf("%d", &a[i]);
scanf("%d", &nb);
for (i = 0; i < nb; i++)
scanf("%d", &b[i]);
if (is_subset(a, na, b, nb))
printf("PODMNOZINA\n");
else
printf("NIE\n");
return 0;
}