凸包(Andrew算法)模板

 

Andrew算法是Graham的变种,相较Graham,其更快,数值稳定性更好。            ——《蓝书》

Andrew 模板  

struct Node{
	int x, y;
}p[maxn], ch[maxn];
bool cmp(Node a, Node b){
	if(a.x == b.x) return a.y < b.y;
	return a.x < b.x;
}
int cross(Node p0, Node p1, Node p2){
	return (p1.x-p0.x) * (p2.y-p1.y) - (p2.x-p1.x) * (p1.y-p0.y); //x1*y2 - x2*y1
}
//凸包边上可以有点,则<,否则<=
int convex_hull(Polygon &pol, int n){
    sort(pol.begin(), pol.end());
    int top = 0;
    Point ch[maxn] = {0};
    for(int i=0; i<n; ++i){
        while(top > 1 && cross(ch[top-1] - ch[top-2], pol[i] - ch[top-1]) < 0) top --;
        ch[top ++] = pol[i];
    }
    int mid = top;
    for(int i=n-2; i>=0; --i){
        while(top > mid && cross(ch[top-1] - ch[top-2], pol[i] - ch[top-1]) < 0) top --;
        ch[top ++] = pol[i];
    }
//    printf("#%d\n", top);
    if(n > 1) top --;
    return top;
}

练习:zoj-3537

凸包+区间dp+三角剖分

可参见:https://blog.youkuaiyun.com/woshi250hua/article/details/7824433

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 305, INF = 1e9;
struct Node{
	int x, y;
}p[maxn], ch[maxn];
int dp[maxn][maxn], cost[maxn][maxn];
bool cmp(Node a, Node b){
	if(a.x == b.x) return a.y < b.y;
	return a.x < b.x;
}
int cross(Node p0, Node p1, Node p2){
	return (p1.x-p0.x) * (p2.y-p1.y) - (p2.x-p1.x) * (p1.y-p0.y); //x1*y2 - x2*y1
}
int abs(int x){
	if(x < 0) return -x;
	return x;
}

int convex_hull(Node *p, int n){
	sort(p, p+n, cmp);
	int top = 1;
	ch[0] = p[0], ch[1] = p[1];	//ch存凸包节点 
	for(int i=0; i<n; ++i){
		while(top && cross(ch[top-1], ch[top], p[i]) <= 0)  top --;
		ch[++ top] = p[i];
	}
	int mid = top;
	for(int i=n-2; i>=0; --i){
		while(top > mid && cross(ch[top-1], ch[top], p[i]) <= 0)	top --;
		ch[++ top] = p[i];
	}
	return top; //凸包节点个数 ,因为0与top存的节点相同,所以不是top+1 
}
int main(){
	int n, MOD;
	while(~scanf("%d%d", &n, &MOD)){
		for(int i=0; i<n; ++i)
			scanf("%d%d", &p[i].x, &p[i].y);
		if(convex_hull(p, n) != n){
			puts("I can't cut.");
			continue;
		}
		for(int i=0; i<n; ++i){
			for(int j=0; j<n; ++j){
				dp[i][j] = INF;
			}
			dp[i][(i+1)%n] = 0;
		}
		memset(cost, 0, sizeof(cost));
		for(int i=0; i<n; ++i)
			for(int j=i+2; j<n; ++j)
				cost[i][j] = cost[j][i] = abs(ch[i].x+ch[j].x) * abs(ch[i].y+ch[j].y) % MOD;
		for(int i=n-3; i>=0; --i){    //i要倒序来保证dp[k][j]先求得
			for(int j=i+2; j<n; ++j)    //j要升序保证dp[i][k]先求得,例dp[1][4]前一定求了dp[1][3]
				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]);
		}
//    	for(int len=1; len<=n; ++len)
//			for(int i=0; i+len<n; ++i){
//				int j = i+len;
//				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]);
	}
	return 0;
}
		
		
		
		

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值