HDU 5510 Bazinga [尺取法]

博客围绕ACM题目展开,输入N个字符串,要输出最大的i,满足存在j < i且Sj不是Si的子串。最初可通过枚举在O(n^2)解决,后引入尺取法思想,利用顺序串的关系,用变量l更新,将时间复杂度降为O(N)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.hdu.edu.cn/showproblem.php?pid=5510

输入N个字符串
标号S1,S2,…,Sn
输出最大的i
满足存在j < i
Sj不是Si的子串

直接枚举
Si和Sj可以在O(n^2)解决这个问题
有没有更快的算法呢?
考虑顺序的三个串
Sa,Sb,Sc, a < b < c
当前情况是
Sa是Sb的子串
现在判断Sc
如果Sa不是Sc的子串,那么Sb必定不是Sc的子串,只需要判断Sb
如果Sa是Sc子串,是就是,如果Sb不是Sc的子串,那么Sc就可能是Ans,
如果Sb是Sc的子串,Sc就不会是Ans
可见Sc只需要判据Sb就好了
这样就可以用一个变量l来更新Sa
时间变为O(N)
这就是尺取法的思想

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>

using namespace std;
const int maxn = 500 + 9;
const int maxl = 2000 + 9;
char a[maxn][maxl];
void solve() {
  memset(a, 0, sizeof(a));
  int n;
  scanf("%d\n", &n);
  for (int i = 0; i < n; i++) {
      gets(a[i]);
  }
  int ans = -1;
  int l = 0;
  for (int r = 1; r < n; r++) {
    while (l < r) {
      if (strstr(a[r], a[l]) != NULL) {
        l++;
      }else {
        ans = r + 1;
        break;
      }
    }
  }
  cout << ans << endl;
}
int main() {
  //freopen("in.txt", "r", stdin);
  int t;
  scanf("%d", &t);
  for (int i = 1; i <= t; i++) {
    printf("Case #%d: ", i);
    solve();
  }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值