50235. Valid Variable Name
難度:4.4/5
藥商為注意一下變數的scope,如果一直需要用到的話就要malloc。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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#define max(a,b) ((a)>(b)?(a):(b))
static inline int is_dig(char c){
return c >= '0' && c <= '9';
}
static inline int is_alp(char c){
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
static inline int is_uds(char c){
return c == '_';
}
int f(char* s){
int cnt = 0;
while(*s != '\0') cnt += (*s), s++;
return cnt % 1000;
}
int is_valid(char* s){
if(*s == '\0' || is_dig(*s)) return 0;
while(*s != '\0'){
if(is_alp(*s) || is_dig(*s) || is_uds(*s)) s++;
else return 0;
}
return 1;
}
typedef struct{
char* table[1000][3];
int cnt[1000][3];
} hash_table;
void init_table(hash_table *h){
memset(h->cnt, -1, sizeof(h->cnt));
}
int insert(hash_table *h, char *s){
int key = f(s);
int exact_idx = -1, first_blank = -1;
for(int i = 0; i < 3; i++){
if(first_blank == -1 && h->cnt[key][i] == -1){
first_blank = i;
}
if(h->cnt[key][i] != -1 && strcmp(s, h->table[key][i]) == 0){
exact_idx = i;
break;
}
}
if(exact_idx != -1){
h->cnt[key][exact_idx]++;
return h->cnt[key][exact_idx];
}
else{
char* new_str = (char*) malloc(sizeof(char) * 22);
strcpy(new_str, s);
h->table[key][first_blank] = new_str;
h->cnt[key][first_blank] = 1;
return 1;
}
}
int main(){
char s[22];
hash_table* h = (hash_table*) malloc(sizeof(hash_table));
init_table(h);
while(scanf("%s", s) != EOF){
if(!is_valid(s)) continue;
int rtv = insert(h, s);
printf("%s %d\n", s, rtv);
}
}