E. Compress Words
time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

Amugae has a sentence consisting of nn words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "samplease".

Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.

Input

The first line contains an integer nn (1≤n≤1051≤n≤105), the number of the words in Amugae's sentence.

The second line contains nn words separated by single space. Each words is non-empty and consists of uppercase and lowercase English letters and digits ('A', 'B', ..., 'Z', 'a', 'b', ..., 'z', '0', '1', ..., '9'). The total length of the words does not exceed 106106.

Output

In the only line output the compressed word after the merging process ends as described in the problem.

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

算法:Hash 或者 KMP

题解:首先分析题目,题目要求我们将每个连续单词相同的前后缀合并成一个,在我们学过的知识里面,字符串前后缀相同的匹配肯定第一想到的就是KMP,对,这题可以用KMP直接做,但是还有一种使代码更加简洁,思路更加简单的方法,那就是用Hash。只要每次查询的时候直接暴力求前后缀相同的最大字符数就行。

Hash:

#include <iostream>
#include <cstdio> using namespace std; typedef long long ll; const int maxn = 1e5+;
const int mod = ;
const int base = ; string ans, s; void solve() {
ll hl = , hr = , tmp = , index = ;
for(int i = ; i < (int)min(ans.size(), s.size()); i++) {
hl = (hl * base + ans[ans.size() - i - ]) % mod; //获取左边数组的后缀Hash值
hr = (s[i] * tmp + hr) % mod; //获取右边数组的前缀Hash值
tmp = (tmp * base) % mod;
if(hl == hr) {
index = i + ; //获取最大的字符匹配位数
}
}
for(int i = index; i < (int)s.size(); i++) {
ans += s[i];
}
} int main() {
int n;
scanf("%d", &n);
cin >> ans;
for(int i = ; i < n; i++) {
cin >> s;
solve();
}
cout << ans << endl;
return ;
}

最新文章

  1. asterisk简单命令
  2. SQL总结(二)连表查询
  3. 【Java】XML解析之DOM
  4. jQuery+Superfish制作下拉菜单
  5. SQL Server 2008 R2 数据库安装
  6. 修改 jquery easyui 表单验证默认的样式
  7. h2database源码浅析:MVTable与MVIndex
  8. Linux 中查看网口流量的利器 -- sar
  9. BZOJ 1026 windy数
  10. javascript为目标位置div等设置高度
  11. Fragment 点击事件的穿透和重叠bug
  12. phpcms和php格式化时间戳
  13. spark idea 的配置问题
  14. day72Django之ORM
  15. Linux 下安装 tomcat
  16. POJ 2243 简单搜索 (DFS BFS A*)
  17. 【C/C++】泛型栈
  18. (转)PWA(Progressive Web App)渐进式Web应用程序
  19. JavaScript控制页码的显示与隐藏
  20. 如何在Ubuntu 14.04 中使用Samba共享文件

热门文章

  1. nodes.js详细安装
  2. 非常有用的pointer-events属性
  3. python 的面试题总汇
  4. java实现spark常用算子之SaveAsTextFile
  5. ASP.NET 打包发布中没有Visual Studio Installer
  6. 在vue-cli项目中使用bootstrap
  7. 使用vue-echarts,需要按需引入
  8. CSS基础:text-overflow:ellipsis溢出文本显示省略号的详细方法_CSS教程
  9. export CommonJS AMD ES6
  10. 第九章&#183;Logstash深入-Logstash配合rsyslog收集haproxy日志