ZOJ - 3537 Cake (區間DP+凸包)
You want to hold a party. Here's a polygon-shaped cake on the table. You'd like to cut the cake into several triangle-shaped parts for the invited comers. You have a knife to cut. The trace of each cut is a line segment, whose two endpoints are two vertices of the polygon. Within the polygon, any two cuts ought to be disjoint. Of course, the situation that only the endpoints of two segments intersect is allowed.
The cake's considered as a coordinate system. You have known the coordinates of vexteces. Each cut has a cost related to the coordinate of the vertex, whose formula is costi, j = |xi + xj| * |yi + yj| % p. You want to calculate the minimum cost.
NOTICE: input assures that NO three adjacent vertices on the polygon-shaped cake are in a line. And the cake is not always a convex.
Input
There're multiple cases. There's a blank line between two cases. The first line of each case contains two integers, N and p (3 ≤ N, p ≤ 300), indicating the number of vertices. Each line of the following N lines contains two integers, x and y (-10000 ≤ x, y ≤ 10000), indicating the coordinate of a vertex. You have known that no two vertices are in the same coordinate.
Output
If the cake is not convex polygon-shaped, output "I can't cut.". Otherwise, output the minimum cost.
Sample Input
3 3
0 0
1 1
0 2
Sample Output
0
思路:先判斷是不是凸包,然後區間DP尋找最優解,DP為最優三角剖分。
最優三角剖分:https://www.cnblogs.com/Jason-Damon/p/3298172.html
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
struct node
{
int x,y;
} a[1005],save[1005];
int dp[1005][1005],cost[1005][1005];
int dis(node d1,node d2,node d3)
{
return d1.x*d2.y+d2.x*d3.y+d3.x*d1.y-d1.x*d3.y-d2.x*d1.y-d3.x*d2.y;
}
int cmp(node a,node b)
{
if(a.y==b.y)
return a.x<b.x;
return a.y<b.y;
}
int Graham(node *p,int n)
{
sort(p,p + n,cmp);
save[0] = p[0];
save[1] = p[1];
int top = 1;
for (int i = 0; i < n; i++)
{
while (top && dis(save[top],p[i],save[top-1]) >= 0) top--;
save[++top] = p[i];
}
int mid = top;
for(int i = n - 2; i >= 0; i--)
{
while (top > mid && dis(save[top],p[i],save[top-1])>=0) top--;
save[++top]=p[i];
}
return top;
}
int n,p;
int Count(node a,node b)
{
return abs(a.x+b.x)*abs(a.y+b.y)%p;
}
int main()
{
while(~scanf("%d%d",&n,&p))
{
for(int i=0; i<n; i++)
scanf("%d%d",&a[i].x,&a[i].y);
if(Graham(a,n)!=n)
{
printf("I can't cut.\n");
continue;
}
memset(cost,0,sizeof(cost));
memset(dp,0x3f,sizeof(dp));
for(int i=0; i<n; i++)
dp[i][(i+1)%n]=0;
for(int i=0; i<n; i++)
{
for(int j=i+2; j<n; j++)
{
cost[i][j]=cost[j][i]=Count(save[i],save[j]);
}
}
for(int len=2; len<n; len++)
{
for(int i=0; i<n; i++)
{
int j=i+len;
if(j>=n)
continue;
for(int k=i+1; k<j; 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]);
}
}