先尝试释放只剩下三个相邻人需要的金币,这三个人在之后尝试释放时可以看做一个整体,然后尝试四个人,,,五个人,,直到求出答案
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#define LL long long
#define MM 10010
#define MAX 1e16
LL dp[MM][MM];
int free_num[MM]; //需要释放的囚犯
using namespace std;
int main()
{
ifstream in ("D:\\钢铁程序员\\程序数据\\985Bride the Prisoners.txt");
if(!in){
cout << "ERROR" << endl ;
return 0;
}
int P, Q;
while(in >> P >> Q)
{
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= Q; ++i)
in >> free_num[i];
free_num[0] = 0;
free_num[Q+1] = P+1;
for (int diff = 2; diff <= Q+1; ++diff)
for (int head = 0; head+diff <= Q+1; ++head)
{
LL temp = MAX;
int tail = head + diff;
for(int v=head+1; v<tail; v++) {
temp = min(temp, dp[head][v]+dp[v][tail]);
cout << head << " " << v << " " << tail << " " << endl;
}
dp[head][tail] = temp + free_num[tail] - free_num[head] - 2;
cout << endl;
}
printf("%d\n", dp[0][Q+1]);
}
in.close();
}