题目链接
https://www.luogu.com.cn/problem/P1622
思路
d p [ i ] [ j ] dp[i][j] dp[i][j]表示释放区间 [ i , j ] [i,j] [i,j]的罪犯所需的最小的肉,状态转移方程为:
d p [ i ] [ j ] = m i n ( d p [ i ] [ j ] , d p [ i ] [ k − 1 ] + d p [ k + 1 ] [ j ] + a [ j + 1 ] − a [ i − 1 ] − 1 − 1 ) dp[i][j] = min(dp[i][j], dp[i][k - 1] + dp[k + 1][j] + a[j + 1] - a[i - 1] - 1 - 1) dp[i][j]=min(dp[i][j],dp[i][k−1]+dp[k+1][j]+a[j+1]−a[i−1]−1−1)。
其中, k k k为分断点, a [ j + 1 ] − a [ i − 1 ] − 1 a[j+1]-a[i-1]-1 a[j+1]−a[i−1]−1表示这个区间内罪犯的人数,最后 − 1 -1 −1是因为不需要给释放的罪犯喂肉。
代码
#include <bits/stdc++.h>using namespace std;#define int long long
#define double long doubletypedef long long i64;
typedef unsigned long long u64;
typedef pair<int, int> pii;const int N = 1e2 + 5, M = 1e6 + 5;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f3f3f3f3f;int p, q;
int a[N];
int dp[N][N];
void solve()
{cin >> p >> q;for (int i = 1; i <= q; i++){cin >> a[i];}a[0] = 0, a[q + 1] = p + 1;for (int len = 1; len <= q; len++){for (int i = 1; i + len - 1 <= q; i++){int j = i + len - 1;dp[i][j] = inf;for (int k = i; k <= j; k++){dp[i][j] = min(dp[i][j], dp[i][k - 1] + dp[k + 1][j] + a[j + 1] - a[i - 1] - 1 - 1);}}}cout << dp[1][q] << endl;
}signed main()
{ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);int test = 1;// cin >> test;for (int i = 1; i <= test; i++){solve();}return 0;
}