CodeForces - 1096D (dp)详解

Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length nn consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaard can be considered hard statements, while har, hart and drah are easy statements.

Vasya doesn't want the statement to be hard. He may remove some characters from the statement in order to make it easy. But, of course, some parts of the statement can be crucial to understanding. Initially the ambiguity of the statement is 00, and removing ii-th character increases the ambiguity by aiai (the index of each character is considered as it was in the original statement, so, for example, if you delete character r from hard, and then character d, the index of d is still 44 even though you delete it from the string had).

Vasya wants to calculate the minimum ambiguity of the statement, if he removes some characters (possibly zero) so that the statement is easy. Help him to do it!

Recall that subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

Input

The first line contains one integer nn (1≤n≤1051≤n≤105) — the length of the statement.

The second line contains one string ss of length nn, consisting of lowercase Latin letters — the statement written by Vasya.

The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤9982443531≤ai≤998244353).

Output

Print minimum possible ambiguity of the statement after Vasya deletes some (possibly zero) characters so the resulting statement is easy.

一道读题自闭的题目。。。看了下题解,才能写。。。

题意:给你一串字符串,每个字符有一个权值,你可以删除某些字符串使它不含子序列hard,求使所删除的字符权值最小的情况。

思路:用dp[i][1]表示前i个不含‘h'的所需最小权值,dp[i][2]表示前i个不含'hr'的最小权值,以此类推。。。剩下的根据代码解释

#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
#define LL long long
const int MAX = 1e5 + 50;
char ch[] = "ahard"; // 存四种字母,第一个a没用的
LL a[MAX]; // 存权值
LL dp[MAX][5];
char s[MAX];
int main(){
	int n;
	scanf("%d", &n);
	scanf("%s", s + 1);
	for(int i = 1; i <= n; i++){
		scanf("%lld", &a[i]);
	}

	for(int i = 1; i <= n; i++){ // 直接处理掉'h'的情况
		if(s[i] == 'h'){
			dp[i][1] = dp[i - 1][1] + a[i];
		} else{
			dp[i][1] = dp[i - 1][1];
		}
	}

	for(int j = 2; j <= 4; j++){
		for(int i = 2; i <= n; i++){
			if(s[i] == ch[j]){ // 若相等,以'har'举例,若想要1到i不含har,则需要1到i - 1不含'hr'或使前面不含har,并删除r.
				dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j] + a[i]);
			} else{
				dp[i][j] = dp[i - 1][j];
			}
		}
	}

	printf("%lld\n", dp[n][4]); // 注意数据范围
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43737952/article/details/89063445