当前位置:网站首页>Introduction to interval DP
Introduction to interval DP
2022-06-24 21:09:00 【GS_ Qiang】
Section dp, seeing the name of a thing one thinks of its function , On the interval dp, The state of most topics is determined by the interval ( Be similar to dp[l][r] This form ) Composed of , That is, we can convert large areas into small areas for processing , Then, after the inter cell processing, the value of the large interval can be obtained by backtracking , There are two main methods , Memory search and recursion .
When using recursion to solve , The key is that recursion is for The sequence in the loop , as well as dp The key to : State transition equation .
Of course, most of the intervals dp They all have their own characteristics , We can consider under what conditions , Large intervals can be transformed into small intervals , Then find out the boundary conditions , Conduct dp solve .
Example 1: Stone merging ( Can form a ring )
Problem Description
Around a circular playground N Rubble (N≤300), Now we need to combine the stones into a pile in order . It is stipulated that only two adjacent piles can be selected at a time to merge into a new pile , And count the new pile of stones , Record as the score of the merger . Make a program , Number of heaps read from file N And the number of stones in each pile (≤20), Choose a plan to merge stones , Make do N-1 The merger , The sum of the scores is the smallest ;
for example , Shown 4 Rubble , Number of stones per pile ( Count from the top pile , Number of punctures in time ) In turn 4594. be 3 The scheme with the smallest sum of sub combined scores :8+13+22=43
Input
The first line is the number of stone piles N;
The second line is the number of stones in each pile , Every two numbers are separated by a space character .
Output
The sum of combined scores is the smallest
SampleInput
4
4 5 9 4
SampleOutput
43
#include<bits/stdc++.h>
using namespace std;
const int N=605;
const int INF=0x3f3f3f3f;
int a[N]={
0};
int sum[N]; // Record prefix and
int dp[N][N]; // Express i->j The minimum value of
int main() {
memset(dp,0,sizeof(dp)); // initialization
int n;
cin >> n;
for(int i=1;i<=n;i++) {
cin >> a[i];
a[i+n]=a[i]; // Because it's circular , So set a[i] The total length of 2n
}
for(int i=1;i<=2*n;i++)
sum[i] = sum[i-1] + a[i]; // The prefix and
for(int dist=2;dist<=n;dist++) {
// Interval length
for(int start=1;start<=2*n-dist+1;start++) {
// The starting point
int end = start+dist-1; // End
dp[start][end] = INF;
for(int k=start;k<end;k++) {
// In the middle
dp[start][end] = min(dp[start][end],dp[start][k]+dp[k+1][end]+sum[end]-sum[start-1]);
}
}
}
int ans=INF;
for(int i=1;i<=n;i++)
ans=min(ans,dp[i][i+n-1]);
cout << ans << endl;
return 0;
}
Example 2: Parentheses matching
We give the following inductive definition of a “regular brackets” sequence: the empty sequence is a regular brackets sequence, if s is a regular brackets sequence, then (s) and [s] are regular brackets sequences, and if a and b are regular brackets sequences, then ab is a regular brackets sequence. no other sequence is a regular brackets sequence For instance, all of the following character sequences are regular brackets sequences: (), [], (()), ()[], ()[()] while the following character sequences are not: (, ], )(, ([)], ([(] Given a brackets sequence of characters a1a2 … an, your goal is to find the length of the longest regular brackets sequence that is a subsequence of s. That is, you wish to find the largest m such that for indices i1, i2, …, im where 1 ≤ i1 < i2 < … < im ≤ n, ai1ai2 … aim is a regular brackets sequence. Given the initial sequence ([([]])], the longest regular brackets subsequence is [([])].
Input
The input test file will contain multiple test cases. Each input test case consists of a single line containing only the characters (, ), [, and ]; each input test will have length between 1 and 100, inclusive. The end-of-file is marked by a line containing the word “end” and should not be processed.
Output
For each input case, the program should print the length of the longest possible regular brackets subsequence on a single line.
SampleInput
((()))
()()()
([]])
)[)(
([][][)
end
SampleOutput
6
6
4
0
6
Code :
#include<iostream>
#include<cstring>
using namespace std;
const int N=305;
const int INF=0x3f3f3f3f;
char a[N];
int dp[N][N];
int main() {
while(cin >> a+1) {
if(a[1] == 'e')break;
memset(dp,0,sizeof(dp));
int n =strlen(a+1);
for(int len=2;len<=n;len++) {
for(int start=1;start<=n-len+1;start++) {
int end = start + len -1;
if(end>n)break;
if(a[start]=='('&&a[end]==')' || a[start]=='['&&a[end]==']')
dp[start][end] = dp[start+1][end-1] + 2;
for(int k=start;k<end;k++) {
dp[start][end] = max(dp[start][end],dp[start][k]+dp[k+1][end]);
}
}
}
cout << dp[1][n] << endl;
}
return 0;
}
Time complexity O(n^3), about n Greater than 1000 May time out when , Quadrilateral inequality can be used for optimization , Reference resources : Quadrilateral inequality optimization
边栏推荐
- data link layer
- [performance tuning basics] performance tuning standards
- Basic properties and ergodicity of binary tree
- Time standard and format
- Memo mode - game archiving
- C语言实现扫雷(简易版)
- IDEA Dashboard
- OSI notes sorting
- How to enhance influence
- After a few years in the testing industry, do you still know a little?
猜你喜欢

Implement the redis simple client customized based on socket

Haitai Advanced Technology | application of privacy computing technology in medical data protection

云计算发展的 4 个阶段,终于有人讲明白了

Pytest test framework II

Curl command

The Google File System (GFS) learning notes

Network security review office starts network security review on HowNet

It was Tencent who jumped out of the job with 26k. It really wiped my ass with sandpaper. It gave me a hand

What does virtualization mean? What technologies are included? What is the difference with private cloud?

After 5 months' test, it took 15K to come for an interview. When I asked, it was not worth even 5K. It was really
随机推荐
Berkeley, MIT, Cambridge, deepmind et d'autres grandes conférences en ligne: vers une IA sûre, fiable et contrôlable
Bean lifecycle flowchart
2021-09-30
Time standard and format
opds sql组件能不能将流程参数通过上下文传给下一个组件
[普通物理] 光栅衍射
C语言实现扫雷(简易版)
Dx12 engine development course progress - where does this course go
得物多活架构设计之路由服务设计
CVPR 2022 remembers Sun Jian! Tongji and Ali won the best student thesis award, and hekaiming was shortlisted
Nifi quick installation (stand-alone / cluster)
伯克利、MIT、剑桥、DeepMind等业内大佬线上讲座:迈向安全可靠可控的AI
Mr. Hu Bo, CIO of weiduomei, a scientific innovator: digitalization is a bloodless revolution, and the correct answer lies in the field of business
After a few years in the testing industry, do you still know a little?
What are the problems with traditional IO? Why is zero copy introduced?
Leetcode (455) - distribute cookies
Open function
红象云腾完成与龙蜥操作系统兼容适配,产品运行稳定
Summary of message protocol problems
Batch capitalization of MySQL table names