CF1200E Compress Words | 字符串hash

传送门

Examples
input 1
5
I want to order pizza
output 1
Iwantorderpizza
input 2
5
sample please ease in out
output 2
sampleaseinout

 

题意:如果前一个单词的后缀和第二个单词的前缀相同,那他们合并的时候省略前缀(看样例)。

题解:我们把前一个的后缀和后一个的前缀进行字符串hash,hash值一样的表示他们后缀和前缀相同可省略,用个pos标记第二个串从哪个位置开始要合并到前一个串上面,hash值相同时更新pos。

  不知道为啥我用char数组写一直tle3,然后改成用string,结果wa1了????显示 “wrong answer Unexpected EOF in the participants output”于是在输入n的时候加了个多组输入终于过了。

代码:

#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1e6 + 10;
const ll P = 127;
const ll mod = 1e9 + 7;
string s,ans;
int main(){
    int n;
    while(~scanf("%d",&n)){
        ans="\0";
        while(n--) {
            cin>>s;
            int ls = s.size(),la = ans.size();
            int len = min(la,ls),pos = 0;
            ll hs = 0,ha = 0,p = 1;
            for (int i = 0; i < len; i++) {
                ha = ((ans[la-1-i]*p%mod)+ha)%mod;
                hs = ((hs*P%mod)+s[i])%mod;
                if (ha == hs) pos = i+1;
                p=p*P%mod;
            }
        ans+=s.substr(pos);
        }
        cout<<ans<<"\n";
    }
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/l999q/p/11340478.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值