SDNU-1101.前缀判断2(set)

SDNU-1101.前缀判断2

Description
由若干字符串组成一个序列,序列中的在前面的项是后面项的前缀。
给定多干个字符串,从中拿出若干项组成满足上述条件的序列,求最长的序列长度。
Input
第一行为一个整数n(1<=n<=1000),之后n行,每行一个字符串,字符串由26个小写字母组成,最长为100。
Output
一个整数,最长的序列长度。
Sample Input
5
a
ab
abc
bc
b
Sample Output
3
Hint

样例中的序列为
a ab abc
本题中,相同的字符串不互为前缀。

跟我上一篇博客“传送门”做法一样,就是我用了结构体,一开始WA是因为遍历的时候想错了。。。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <set>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
struct node
{
    string s;
    set<string> q;//存储s的所有前缀
    int sum=1;
} ss[1005];
int main()
{
    int n;
    cin>>n;
    for (int i=0; i<n; i++)
    {
        cin>>ss[i].s;
        for (int j=1; j<ss[i].s.length(); j++)
        {
            string str=ss[i].s.substr(0,j);
            ss[i].q.insert(str);//不明白的请看上一篇博客
        }
    }
    int ans=0;
    for (int i=1; i<n; i++)
    {
        for (int j=0; j<i; j++)//这个一开始第二层遍历我没写,就Wa
        {
            if (ss[i].q.count(ss[j].s))
                ss[i].sum=ss[j].sum+1;//这里我觉得很精妙,☺
            ans=max(ans,ss[i].sum);
        }
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43892298/article/details/87925386