【Codeforces 1096D】Easy Problem
生活随笔
收集整理的這篇文章主要介紹了
【Codeforces 1096D】Easy Problem
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【鏈接】 我是鏈接,點我呀:)
【題意】
讓你將一個字符串刪掉一些字符。
使得字符串中不包含子序列"hard"
刪掉每個字符的代價已知為ai
讓你求出代價最小的方法.
【題解】
設dp[i][j]表示前i個字符,已經和"hard"匹配前j個的最小花費。
對于dp[i][j]
對s[i+1]分類討論
①s[i+1]不刪
那么有兩種情況
第一種:s[i+1]和"hard"的第j+1個字符匹配
第二種:..xxxxx不匹配
則分別轉移到dp[i+1][j+1]和dp[i+1][j]
②s[i+1]刪掉
轉移到dp[I+1][j]且用dp[i][j]+a[i+1]嘗試轉移。
【代碼】
import java.io.*; import java.util.*;public class Main {static InputReader in;static PrintWriter out;public static void main(String[] args) throws IOException{//InputStream ins = new FileInputStream("E:\\rush.txt");InputStream ins = System.in;in = new InputReader(ins);out = new PrintWriter(System.out);//code start from herenew Task().solve(in, out);out.close();}static int N = (int)1e5;static class Task{int n;String s;long a[] = new long[N+10];String goal=new String(" hard");long dp[][] = new long[N+10][10];public void solve(InputReader in,PrintWriter out) {n = in.nextInt();s = in.next();s = " "+s;for (int i = 1;i <=n;i++) a[i] = in.nextLong();for (int i = 0;i <= N;i++) for (int j = 0;j <= 8;j++)dp[i][j] = (long)(1e17);dp[0][0] = 0;for(int i = 0;i < n;i++)for (int j = 0;j <= 3;j++) {//第i+1個不刪if (s.charAt(i+1)==goal.charAt(j+1)) {dp[i+1][j+1] = Math.min(dp[i+1][j+1], dp[i][j]);}else {dp[i+1][j] = Math.min(dp[i+1][j], dp[i][j]);}//第i+1個刪掉dp[i+1][j] = Math.min(dp[i+1][j], dp[i][j]+a[i+1]);}long ans = dp[n][0];for (int i = 1;i <= 3;i++) {ans = Math.min(ans, dp[n][i]);}out.println(ans);}}static class InputReader{public BufferedReader br;public StringTokenizer tokenizer;public InputReader(InputStream ins) {br = new BufferedReader(new InputStreamReader(ins));tokenizer = null;}public String next(){while (tokenizer==null || !tokenizer.hasMoreTokens()) {try {tokenizer = new StringTokenizer(br.readLine());}catch(IOException e) {throw new RuntimeException(e);}}return tokenizer.nextToken();}public int nextInt() {return Integer.parseInt(next());}public long nextLong() {return Long.parseLong(next());}} }轉載于:https://www.cnblogs.com/AWCXV/p/10527356.html
總結
以上是生活随笔為你收集整理的【Codeforces 1096D】Easy Problem的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017沈阳站 Tree
- 下一篇: 爬取今日头条财经版块新闻