最短覆盖子串问题解析

编程入门 行业动态 更新时间:2024-10-24 07:31:59

<a href=https://www.elefans.com/category/jswz/34/1769359.html style=最短覆盖子串问题解析"/>

最短覆盖子串问题解析

问题描述:

给定两个字符串 a a a b b b, 试求字符串 a a a 的一个字串 s s s,使得 s s s 满足

  1. 该串包含 b b b 中出现的所有字符
  2. 满足条件1使该串长度最小

问题分析:

遍历 b b b ,储存所有出现过的字符。
l r 表示 s s s 在的 a a a 中的两个端点。
当 s s s 未满足条件1时 r++ , 满足条件1时 l++并记录答案。

例题

洛谷 P1638 逛画展
代码如下:

#pragma warning(disable:4996)
#include<stdio.h>
const int MAXn = 1e6 + 5;
const int MAXm = 2e3 + 5;
int n, m, master[MAXm], a[MAXn];struct ScalableInterval {int l = 1, r = 1, sum = 0;bool vis[MAXm];bool check(int i, int k) {master[i] += k;if (master[i] == 0 && vis[i]) {vis[i] = false;sum--;}else if (vis[i] == 0 && master[i]) {vis[i] = true;sum++;}//	printf("%d %d\n", i, k);if (sum == m)return true;else return false;}
}SI;
struct as {int l = 1, r = MAXn;
}ans;int main() {scanf("%d %d", &n, &m);for (int i = 1; i <= n; i++)scanf("%d", a + i);while (SI.l <= n && SI.r <= n) {while (!SI.check(a[SI.r++], 1));while (SI.check(a[SI.l++], -1));if (SI.r > n + 1|| SI.l > n )break;if (SI.r - SI.l < ans.r - ans.l) {ans.l = SI.l;ans.r = SI.r;}}    printf("%d %d", ans.l - 1, ans.r - 1);return 0;
}

更多推荐

最短覆盖子串问题解析

本文发布于:2024-02-10 20:03:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1677018.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最短

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!