poj 2418 Hardwood Species 快排

原题链接: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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值