GCJ 2009 Bribe the Prisoners

区间DP……但是细节处理比较多,代码要一些技巧……算水题吧


#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cmath>
#include <vector>
using namespace std;

#define LL long long
void nextInt(int &x)
{
	scanf("%d", &x);
}
void nextInt(int &x, int &y)
{
	scanf("%d%d", &x, &y);
}


const LL maxn = 500;
int n;
int p;
int a[maxn];
int f[maxn][maxn];

void init()
{
	nextInt(n, p);
	for (int i = 1; i <= p; ++ i)
		nextInt(a[i]);
	a[0] = 0;
	a[p + 1] = n + 1;
	sort(a, a + 2 + p);
	//for (int i = 0; i <= p + 1; ++ i)	cout<<a[i]<<endl;
	memset(f, 0, sizeof(f));
	for (int w = 2; w <= p + 1; ++ w)//长度
		for (int i = 0; w + i <= p + 1; ++ i)//开始位置
		{
			//(i, i + w)区间, 实际可用区间为[i + 1, i + w - 1]
			f[i][i + w] = a[w + i] - a[i] - 2;
			int tmp = 0x7fffffff;
			for (int k = i + 1; k <= i + w - 1; ++ k)
			{
				tmp = min(tmp, f[i][k] +  f[k][i + w]);
			}
			f[i][i + w] += tmp;
		}
	printf("%d\n", f[0][p + 1]);
}

int main()
{
	freopen("a.in","r",stdin);
	freopen("a.txt","w",stdout);
	LL sb;
	scanf("%lld", &sb);
	for (int i = 1; i <= sb; ++ i)
	{
		printf("Case #%d: ", i);
		init();
	}
	return 0;
}


你可能感兴趣的:(GCJ 2009 Bribe the Prisoners)