题意:给定n个点的坐标,先问这些点是否能组成一个凸包,如果是凸包,问用不相交的线来切这个凸包使得凸包只由三角形组成,根据costi, j = |xi + xj| * |yi + yj| % p算切线的费用,问最少的切割费用。
思路:先找个凸包模板打上,然后区间DP即可
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
#define MAX 1000
#define INF 1000000000
#define min(a,b) ((a)<(b)?(a):(b))
struct point{
int x,y;
}p[MAX];
int cost[MAX][MAX],n,m;
int dp[MAX][MAX];
int abs(int x) {
return x < 0 ? -x : x;
}
point save[400],temp[400];
int xmult(point p1,point p2,point p0){
return (p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y);
}
bool cmp(const point& a,const point &b){
if(a.y == b.y)return a.x < b.x;
return a.y < b.y;
}
int Graham(point *p,int n) {
int i;
sort(p,p + n,cmp);
save[0] = p[0];
save[1] = p[1];
int top = 1;
for(i = 0;i < n; i++){
while(top && xmult(save[top],p[i],save[top-1]) >= 0)top--;
save[++top] = p[i];
}
int mid = top;
for(i = n - 2; i >= 0; i--){
while(top>mid&&xmult(save[top],p[i],save[top-1])>=0)top--;
save[++top]=p[i];
}
return top;
}
int Count(point a,point b) {
return (abs(a.x + b.x) * abs(a.y+b.y)) % m;
}
int main()
{
int i,j,k,r,u;
while (scanf("%d%d",&n,&m) != EOF) {
for (i = 0; i < n; ++i)
scanf("%d%d",&p[i].x,&p[i].y);
int tot = Graham(p,n); //求凸包
if (tot < n) printf("I can't cut.\n");
else {
memset(cost,0,sizeof(cost));
for (i = 0; i < n; ++i)
for (j = i + 2; j < n; ++j)
cost[i][j] = cost[j][i] = Count(save[i],save[j]);
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j)
dp[i][j] = INF;
dp[i][(i+1)%n] = 0;
}
for (i = n - 3; i >= 0; --i) //注意这三个for循环的顺序
for (j = i + 2; j < n; ++j) //因为要保证在算dp[i][j]时dp[i][k]和dp[k][j]时已经计算,所以i为逆序,j要升序
for (k = i + 1; k <= j - 1; ++k)
dp[i][j] = min(dp[i][j],dp[i][k]+dp[k][j]+cost[i][k]+cost[k][j]);
printf("%d\n",dp[0][n-1]);
}
}
}