【DP】 HDOJ 3480 Division

之前写过这题的斜率优化。。。其实这题还可以用四边形优化写。。。。

#include <iostream>
#include <queue> 
#include <stack> 
#include <map> 
#include <set> 
#include <bitset> 
#include <cstdio> 
#include <algorithm> 
#include <cstring> 
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 10005
#define maxm 1000005
#define eps 1e-10
#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid 
#define rson o<<1 | 1, mid+1, R
#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
void scanf(int &__x){__x=0;char __ch=getchar();while(__ch==' '||__ch=='\n')__ch=getchar();while(__ch>='0'&&__ch<='9')__x=__x*10+__ch-'0',__ch = getchar();}
LL gcd(LL _a, LL _b){if(!_b) return _a;else return gcd(_b, _a%_b);}
// head

int dp[maxn][maxn];
int s[maxn][maxn];
int val[maxn];
int n, m;

int cmp(int a, int b)
{
	return a < b;
}

void read(void)
{
	scanf("%d%d", &n, &m), m--;
	for(int i = 1; i <= n; i++) scanf("%d", &val[i]);
	sort(val+1, val+n+1, cmp);
}

void work(void)
{
	for(int i = 0; i <= m; i++)
		for(int j = 0; j <= n; j++)
			dp[i][j] = INF;
	for(int i = 1; i <= n; i++) dp[0][i] = (val[i] - val[1]) * (val[i] - val[1]), s[0][i] = 1;
	for(int i = 1; i <= m; i++) s[i][n+1] = n;
	for(int i = 1; i <= m; i++)
		for(int j = n; j >= 1; j--)
			for(int k = s[i-1][j]; k <= s[i][j+1]; k++)
				if(dp[i][j] > dp[i-1][k] + (val[j] - val[k+1]) * (val[j] - val[k+1])) {
					dp[i][j] = dp[i-1][k] + (val[j] - val[k+1]) * (val[j] - val[k+1]);
					s[i][j] = k;
				}
	printf("%d\n", dp[m][n]);
}

int main(void)
{
	int _, __;
	while(scanf("%d", &_)!=EOF) {
		__ = 0;
		while(_--) {
			read();
			printf("Case %d: ", ++__);
			work();
		}
	}

	return 0;
}


你可能感兴趣的:(dp,HDU)