原题链接:http://poj.org/problem?id=2418
写了两种方法,快排,Treap。
还是平衡树要快一些。注意我用gcc提交wa用c却过了,/(ㄒoㄒ)/~~
具体如下:
快排:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef char State[33];
State st[1000010];
int cmp(const char* src, const char *_src){
return strcmp((char *)src, (char *)_src);
}
int main(){
State ret, buf;
int i, k, cnt = 0;
while (gets(ret)) strcpy(st[cnt++], ret);
qsort(st, cnt, sizeof(st[0]), cmp);
i = 0;
while (i < cnt){
strcpy(buf, st[i]), k = 0;
for (; 0 == strcmp(buf, st[i]); i++) k++;
printf("%s %.4lf\n", buf, (double)k * 100 / cnt);
}
return 0;
}
平衡树
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct _treap{
int cnt, fix;
char buf[33];
struct _treap *left, *right;
}treap, *Treap;
treap _node[1000010];
int sz = 0, cnt = 0;
int _random(){
static int x = 1840828537;
x += (x << 2) | 1;
return x;
}
void rotate_right(Treap *T){
Treap k = (*T)->left;
(*T)->left = k->right;
k->right = *T;
*T = k;
}
void rotate_left(Treap *T){
Treap k = (*T)->right;
(*T)->right = k->left;
k->left = *T;
*T = k;
}
void insert(Treap *T, char *src, int fix){
if (*T == NULL){
*T = &_node[sz++];
(*T)->left = (*T)->right = NULL;
strcpy((*T)->buf, src), (*T)->cnt = 1, (*T)->fix = fix;
}
else if (-1 == strcmp(src, (*T)->buf)){
insert(&((*T)->left), src, fix);
if ((*T)->left->fix < (*T)->fix)
rotate_right(T);
}
else if (1 == strcmp(src, (*T)->buf)){
insert(&((*T)->right), src, fix);
if ((*T)->right->fix < (*T)->fix)
rotate_left(T);
} else {
(*T)->cnt++;
return;
}
}
void query(Treap T){
if (T != NULL){
query(T->left);
printf("%s %.4lf\n", T->buf, (double)T->cnt * 100 / cnt);
query(T->right);
}
}
int main(){
char ret[33];
Treap root = NULL;
while (gets(ret)){
insert(&root, ret, _random());
cnt++;
}
query(root);
return 0;
}