BZOJ 4709: [Jsoi2011]柠檬【斜率优化

80 篇文章 0 订阅
16 篇文章 0 订阅

发现……每一段的开头结尾应该是同一个颜色才会最优

于是……就是个naive的斜率优化dp了,斜率单增,对于每种颜色,点的横坐标也有序,要最大化截距

…于是…单调栈……


#include<bits/stdc++.h>
#define MAXN 100005
#define MAXS 10004
using namespace std ;	int n ;
const double eps = 1e-7 ;
const double inf = 1e18 ;
inline int read() {
	register int ch = getchar() ;
	while (!isdigit(ch))	ch = getchar() ;
	register int rtn = 0 ;
	while (isdigit(ch))	rtn = rtn*10 + ch - '0', ch = getchar() ;
	return rtn ;
}

int pre[MAXN], pos[MAXS], col[MAXN] ;
int cnt[MAXN] ;
long long f[MAXN] ; 

vector<int> que[MAXS] ;
int top[MAXS] ;

long long X[MAXN], Y[MAXN] ;
inline double get_K(int u, int v) {
	if (X[u] == X[v])	return inf ;
	return ((double)Y[u] - Y[v]) / ((double)X[u] - X[v]) ; 
}

int main() {
	//freopen("1.in","r",stdin) ;

	n = read() ;
	for (int i=1; i<=n; ++i) {
		col[i] = read() ;
		pre[i] = pos[ col[i] ] ;
		pos[ col[i] ] = i ;
		cnt[i] = cnt[ pre[i] ] + 1 ;
	}

	memset(pos,0,sizeof pos) ;
	for (int i=1; i<=n; ++i)
		if (!pos[col[i]])
			que[col[i]].push_back(0), pos[ col[i] ] = 1 ;
	
	for (int i=1; i<=n; ++i) {
		int x = col[i], k = 2*cnt[i] ;
		
		X[i] = 1ll*cnt[ pre[i] ] * col[i] ;
		Y[i] = 1ll*col[i] * cnt[ pre[i] ] * cnt[ pre[i] ] + f[i-1] ;

		while ( top[x] > 0 && get_K ( que[x][ top[x]-1 ] , que[x][ top[x] ] ) < get_K ( que[x][ top[x] ], i )-eps )
			--top[x], que[x].pop_back() ;
		que[x].push_back(i), ++top[x] ;		
		
//		printf("i = %d\n",i) ;
//		printf("top = %d\n",top[x]) ;
//		printf("%d %d\n",que[x][ top[x]-1 ], que[x][ top[x] ] ) ;
		while ( top[x] > 0 && get_K ( que[x][ top[x]-1 ] , que[x][ top[x] ] ) - eps < k )
			--top[x], que[x].pop_back() ;
		int j = que[x][ top[x] ] ;
		f[i] = 1ll*col[i]*cnt[i]*cnt[i] + ( -2ll*cnt[i]* ( cnt[ pre[j] ] * col[j] ) + 1ll * col[j] * cnt[ pre[j] ] * cnt[ pre[j] ] + f[j-1] ) ;
	}

//	for (int i=1; i<=n; ++i)	printf("%lld ",f[i]) ;
//	puts("") ;
	printf("%lld\n",f[n]) ;

	return 0 ;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值