HUST 1004 String Compare(字符串前缀对)

来源:互联网 发布:java构造函数的特点 编辑:程序博客网 时间:2024/06/05 18:41

题目链接:http://acm.hust.edu.cn/problem.php?id=1004

Maybe there are 750,000 words in English and some words are prefix of other words, for example: the word "acm" can be treat as one prefix of "acmicpc". What's more, most of such pairs of words have relationship between them. Now give you a dictionary, your work is to tell me how many such pairs.


题目意思很简单,开始一看,想都没想就trie树,后来MLE了才改成现在的代码

首先排序,然后前缀关系一定相邻,那么从当前位置向后找,找的时候用二分

排序一遍,遍历+二分一遍

n*logn*30

#include <string.h>#include <algorithm>#include <stdio.h>#include <iostream>using namespace std;struct point{    char str[31];    int len;}po[51000];int n;long long ans;bool cmp(const point &a,const point &b){    return strcmp(a.str,b.str)<0;}bool is_ok(char *first,char *second,char num){    for(int i=0;i<num;i++)    if(first[i]!=second[i]) return false;    return true;}int upbound(int pos,int left,int right){    int mid,ans=0;    while(left <= right){        mid=(left+right)>>1;        if(po[pos].len > po[mid].len){            right=mid-1;            continue;        }        if(is_ok(po[pos].str,po[mid].str,po[pos].len)){            left=mid+1;            ans=max(mid,ans);        }        else right=mid-1;    }    return ans;}int main(){    int i,j,k,t,now;    scanf("%d",&t);    while(t--){        scanf("%d",&n);        ans=0;        for(i=0;i<n;i++){            scanf("%s",po[i].str);            po[i].len=strlen(po[i].str);        }        sort(po,po+n,cmp);        for(i=0;i<n;i++){            now=upbound(i,i,n-1);            ans+=(now-i);        }        if(ans > 11519) ans%=11519;        printf("%lld\n",ans);    }    return 0;}


0 0
原创粉丝点击