upc 6597 Don't Be a Subsequence(dp)

本文介绍了一道算法题的解决思路,目标是寻找相对于给定字符串A的最短且字典序最小的非子序列字符串。利用动态规划与辅助数组Next实现高效求解。

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

                                          6597: Don't Be a Subsequence

                                                                  时间限制: 1 Sec  内存限制: 128 MB
 

题目描述

A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, arc, artistic and (an empty string) are all subsequences of artistic; abc and ci are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.

Constraints
1≤|A|≤2×105
A consists of lowercase English letters.

 

输入

Input is given from Standard Input in the following format:
A

 

输出

Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.

 

样例输入

atcoderregularcontest

 

样例输出

b

 

提示

The string atcoderregularcontest contains a as a subsequence, but not b.

 

 

 

 

题目大意:

找一个字符串,不是s的子串,长度最短,字典序最小。

 

 

 

分析:

这个题不会, 看了题解竟然可以用dp做,很是佩服

Next[i][j] 表示  位置i之后  'a' - 'z' 第一次出现的位置

dp[i]  表示   位置i之后  最短的非子序列长度 

最后通过Next数组 找到dp[0]个字母, 字母从小到达大找, 输出就行了

 

 

 

 

 

AC代码:

#include <bits/stdc++.h>
#define mset(a, x) memset(a, x, sizeof(a))
using namespace std;
typedef long long ll;
const int N = 1e5 + 5;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
string str;
int dp[2 * N];
int Next[2 * N][30];
int a[30];
int main() {
	std::ios::sync_with_stdio(false);
	cin >> str;
	for (int i = 0; i < 26; i++) {
		a[i] = str.length();
	}
	for (int i = str.length() - 1; i >= 0; i--) {
		a[str[i] - 'a'] = i;
		for (int j = 0; j < 26; j++) {
			Next[i][j] = a[j];
		}
		dp[i] = INF;
	}
	dp[str.length()] = 1;
	for (int i = str.length() - 1; i >= 0; i--) {
		for (int j = 0; j < 26; j++) {
			dp[i] = min(dp[i], dp[Next[i][j] + 1] + 1);
		}
	}
	int Index = 0;
	for (int i = dp[0]; i >= 0; i--) {
		for (int j = 0; j < 26; j++) {
			if (dp[Index] == dp[Next[Index][j] + 1] + 1) {
				cout << (char) (j + 'a');
				Index = Next[Index][j] + 1;
				break;
			}
		}
	}
	cout << endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值