您的位置:首页 > 其它

ZOJ 3826(字符串hash)

2015-08-01 09:55 344 查看
本体的意思是给了一个{ key:value , key:value ..... }的串,且value的形式可以也是这个形式(即是递归的),那么给定一些key1.key2.key3...类似如此的键值查询,让输出对饮键下的value,(没有该键值输出Error!)

example:

输入 :

{"hm":"Edward","stu":{"stu01":"Alice","stu02":"Bob"}}

4

"hm"

"stu"

"stu"."stu01"

"students"

输出为:

"Edward"

{"stu01":"Alice","stu02":"Bob"}

"Alice"

Error!

对于本题目,查了一下,竟然都是对每个链状字符串(把从根key到目标key的所有字符串看做一条链),由于“ : ”最多为10000个,那么意味着最终要保存的hash值也就只有10000条,用hash的话冲突的概率极低,所以大家就妥妥的过了,只不过坑了乖孩子,不敢这么玩的人可就惨了。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include <vector>
#include <queue>
#include <map>
#include <string>
using namespace std;
#define ls (rt<<1)
#define rs (ls|1)
#define fst first
#define snd second
#define lson l,mid,ls
#define rson mid+1,r,rs
#define rep(i,n) for(int i=0;i<(int)n;i++)
#define rep1(i,x,y) for(int i=x;i<=(int)y;i++)
#define clr(a, x) memset(a, x, sizeof a)
typedef long long LL;
typedef long long ll;
typedef pair<int,int> pii;
const int N = 1010101;
const int BASE = 131;

inline int id(char c){return ((int)c)%(BASE); }
int p;
char str
,src
;
map<LL,pii> M;
void build(LL pre){
    while(str[p]!='}'){
        int now = pre;
        if(str[++p]=='}') return ;
        while(str[p]!=':'){
           now=now*BASE+id(str[p]);
           p++;
        }
        int st = ++p;
        if(str[p]=='{'){
           build(now*BASE+id('.'));
        }
        else {
           while(str[p+1]!=','&&str[p+1]!='}') p++;
        }
        M[now]=pii(st,p++);
    }
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--){
       M.clear();
       scanf("%s",str);
       p = 0; build(0);
       int Q; scanf("%d",&Q);
       while(Q--){
           scanf("%s",src);
           int len = strlen(src),res=0;
           rep(i,len) res=res*BASE+id(src[i]);
           if(!M.count(res)) printf("Error!\n");
           else {
           pii te = M[res];
           rep1(i,te.first,te.second)  printf("%c",str[i]);
           printf("\n");
           }
       }
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: