HDU 5510---Bazinga(指针模拟)
Posted 茶飘香~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 5510---Bazinga(指针模拟)相关的知识,希望对你有一定的参考价值。
题目链接
http://acm.hdu.edu.cn/search.php?action=listproblem
Problem Description
Ladies and gentlemen, please sit up straight.
Don‘t tilt your head. I‘m serious.
For n given strings S1,S2,?,Sn, labelled from 1 to n, you should find the largest i (1≤i≤n) such that there exists an integer j (1≤j<i) and Sj is not a substring of Si.
A substring of a string Si is another string that occurs in Si. For example, ``ruiz" is a substring of ``ruizhang", and ``rzhang" is not a substring of ``ruizhang".
Don‘t tilt your head. I‘m serious.
For n given strings S1,S2,?,Sn, labelled from 1 to n, you should find the largest i (1≤i≤n) such that there exists an integer j (1≤j<i) and Sj is not a substring of Si.
A substring of a string Si is another string that occurs in Si. For example, ``ruiz" is a substring of ``ruizhang", and ``rzhang" is not a substring of ``ruizhang".
Input
The first line contains an integer t (1≤t≤50) which is the number of test cases.
For each test case, the first line is the positive integer n (1≤n≤500) and in the following n lines list are the strings S1,S2,?,Sn.
All strings are given in lower-case letters and strings are no longer than 2000 letters.
For each test case, the first line is the positive integer n (1≤n≤500) and in the following n lines list are the strings S1,S2,?,Sn.
All strings are given in lower-case letters and strings are no longer than 2000 letters.
Output
For each test case, output the largest label you get. If it does not exist, output −1.
Sample Input
4
5
ab
abc
zabc
abcd
zabcd
4
you
lovinyou
aboutlovinyou
allaboutlovinyou
5
de
def
abcd
abcde
abcdef
3
a
ba
ccc
Sample Output
Case #1: 4
Case #2: -1
Case #3: 4
Case #4: 3
Source
Recommend
题意:输入n 然后输入n个字符串,求最大的i 要求1~i-1中有一个串不是i的子串?
思路:分析复杂度可知这n个字符串比较次数只能是O(n) 那么发现可以用指针模拟的办法解决。具体做法:定义l和r 如果l是r的子串,那么l++ 继续判断l是否是r的子串,否则ans=r, 为什么这样呢? 如果l是r的子串那么l++ 由它可知1~l-1 这些串一定是l~r这些串中一些串的子串,那么1~l-1这些串不必再和r后面的串进行比较;
代码如下:
#include <iostream> #include <algorithm> #include <stdio.h> #include <cstring> #include <queue> using namespace std; typedef long long LL; char s[600][2005]; int nex[2005]; void makeNext(char p[]) { int q,k; int m=strlen(p); nex[0]=0; for(q=1,k=0; q<m; ++q) { while(k>0&&p[q]!=p[k]) k=nex[k-1]; if(p[q]==p[k]) k++; nex[q]=k; } } int calc(int x,int y) { makeNext(s[x]); int l=strlen(s[x]); int len=strlen(s[y]); int q,k; for(q=0,k=0; q<len; q++) { while(k>0&&s[y][q]!=s[x][k]) k=nex[k-1]; if(s[y][q]==s[x][k]) k++; if(k>=l) return 1; } return 0; } int main() { int T,Case=1; cin>>T; while(T--) { int n; scanf("%d",&n); for(int i=1; i<=n; i++) scanf("%s",s[i]); int l = 1, r = 2, ans = -1; while(r <= n) { while(l < r) { if(calc(l,r)) l++; else { ans=r; break; } } r++; } printf("Case #%d: %d\n",Case++,ans); } return 0; }
以上是关于HDU 5510---Bazinga(指针模拟)的主要内容,如果未能解决你的问题,请参考以下文章