BAZINGA

9243: BAZINGA

时间限制: 2 Sec  内存限制: 128 MB
提交: 345  解决: 39
[提交] [状态] [讨论版] [命题人:admin]

题目描述

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) such that Sj is not a substring of Si . For example, “izh” is a substring of “ruizhang”,and “zrui” is not a substring of “ruizhang”.

输入

The first line contains an integer t (1 ≤ t ≤ 100) 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, output the largest label you get. If it does not exist,
output −1.

样例输入

3
4
aa
ab
aba
aaba
5
a
ba
acba
abaaacaabaa
dabadaacasabaza
3
a
ba
ccc

样例输出

Case #1: 2
Case #2: -1
Case #3: 3

 

直接扫O(n*n),然后从后往前扫,一系列操作,优化到了O(n)

 

从后往前,两两比较,如果符合check,说明当前串肯定是后面的串的子序列,如果这样扫完了所有的串,说明

每一个串前面的串肯定都是自己的子序列,所以输出-1

 

否则的话假设i和i-1位置不符合check,那么就是i及其后面所有的串可能是答案,那么只要扫i到n之间的串即可,

但是这样并不是最优,因为这样直接扫数组还是O(n*n),设两个变量l,r指向i的前后,即l = i-1,r = i+1

那么,判断 r 符不符合的时候只需要扫描 l 及其前面的就好了,因为前面第一步操作保证了 i 之后到 r 的所有串都是 r 的子序列

如果某个时刻check(r,l)不符合了,说明当前的r可能是答案,所以r++看是否后面能够取到更大的答案,否则就l--,一直向前比对

 

那么最后出来的 r 并不是答案,因为这样匹配的时候向后扫,不符合r++,那么最后r要么是n+1(对于最后一个串,其不符合)

要么就是当前 r 在其前面所有的串都可以是 r 的子序列,所以 答案是 r-1

 

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
char a[505][4005];
bool check(char a[],char b[]){
    int i,j;i = j = 0;
    while(a[i]&&b[j]){if(a[i]==b[j])j++;i++;}
    return !b[j];
}
int main()
{
    int t,n;
    scanf("%d",&t);
    for(int Case = 0;Case<t;Case++)
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
            scanf("%s",a[i]);
        int l,r,i;
        for(i=n;i-1;i--)
            if(!check(a[i],a[i-1]))break;
        l = i-1, r = i+1;
        while(l && r<=n)
        {
            while(r<=n && !check(a[r],a[l]))
                r++;
            l--;
        }
        printf("Case #%d: %d\n",Case+1,i==1?-1:r-1);
    }
 
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值