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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值