C - Bazinga HDU - 5510 (搜索子串)

Ladies and gentlemen, please sit up straight.
Don’t tilt your head. I’m serious.
For nn given strings S1,S2,⋯,SnS1,S2,⋯,Sn, labelled from 11 to nn, you should find the largest i (1≤i≤n) such that there exists an integer j (1≤j<i)and SjSj is not a substring of SiSi.

A substring of a string SiSi is another string that occurs in SiSi. For example, ruiz" is a substring ofruizhang”, and rzhang" is not a substring ofruizhang”.
Input
The first line contains an integer t (1≤t≤50)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)n (1≤n≤500) and in the following nn lines list are the strings S1,S2,⋯,SnS1,S2,⋯,Sn.
All strings are given in lower-case letters and strings are no longer than 20002000 letters.
Output
For each test case, output the largest label you get. If it does not exist, output −1−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

补充

strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。

思路

从最后一个最大的字符串往前遍历,判断它前面一个字符串是否是它的子串,如果是,那么接着寻找(利用子串的传递性,如果每一个字符串前面一个都是它的子串,那么最小的那个也一定是这个最大字符串的子串),直到找到一个字符串不是它前面一个字符串的子串。这时候需要往这个子串后面遍历,判断它是不是前面大字符串的子串,如果不是,那么继续循环,直到找到一个大字符串不是它的母串(或者字符串全部遍历),那么记录下这个标号,他就是我们要找的那个字符串编号(由于我们用二维数组储存时,从0开始,所以最后的答案还要+1)。
因为题目要求如果不存在的话,输出-1,所以我们给ans的初值最好设置为-2,那么如果没有找到,-2+1=-1,直接输出即可。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
char s[505][2005];
int main()
{
    int t;
    while(scanf("%d", &t) != EOF){
        int kase = 0;
        while(t--){
            int n;
            scanf("%d", &n);
            for(int i = 0; i < n; i++)
                scanf("%s", s[i]);
            int ans = -2;
            for(int i = n - 1; i > 0; i--){
                if(!strstr(s[i], s[i - 1])){
                        ans = max(ans,i);
                    for(int j = i + 1; j < n; j++){
                        if(!strstr(s[j], s[i - 1]))
                            ans = max(ans,j);
                    }
                }
            }
            printf("Case #%d: %d\n", ++kase, ans + 1);
        }
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值