题解:P13439 [GCJ 2009 #1C] Bribe the Prisoners
__QAQ______ · · 题解
P13439 [GCJ 2009 #1C] Bribe the Prisoners
老师讲了区间动态规划,所以找了道题复习:传送门。
思路
这题用的是区间动态规划,令
其中
下面是通过记录和代码。
记录。
#include<bits/stdc++.h>
using namespace std;
const int N=1e3+1;
int n,m,s;
int need[N];//需释放的囚犯数
int f[N][N];//区间dp数组
int main(){
ios::sync_with_stdio(0);//加快读入
cin.tie(0);cout.tie(0);
cin>>s;
for(int a11=0;a11<s;a11++){
cin>>n>>m;//输入牢房数n和需释放的囚犯数m
for(int i=1;i<=m;i++){
cin>>need[i];//输入需释放的囚犯编号
}
sort(need+1,need+m+1);//排序,后期更方便状态转移
need[0]=0,need[m+1]=n+1;//假设0号牢房与m+1号牢房均有人,方便状态转移
for(int len=1;len<=m;len++){
for(int l=1;l+len-1<=m;l++){
int r=l+len-1;
f[l][r]=INT_MAX;
for(int k=l;k<=r;k++){
f[l][r]=min(f[l][r],f[l][k-1]+f[k+1][r]+need[r+1]-need[l-1]-1-1);
//状态转移方程
}
}
}
cout<<"Case #"<<a11+1<<": "<<f[1][m]<<endl;//输出
}
return 0;//好习惯
}