其他分享
首页 > 其他分享> > [USACO07NOV]Telephone Wire G 题解

[USACO07NOV]Telephone Wire G 题解

作者:互联网

题目描述

Farmer John's cows are getting restless about their poor telephone service; they want FJ to replace the old telephone wire with new, more efficient wire. The new wiring will utilize \(N\) \((2 ≤ N ≤ 100,000)\) already-installed telephone poles, each with some heighti meters \((1 ≤ heighti ≤ 100)\). The new wire will connect the tops of each pair of adjacent poles and will incur a penalty cost C × the two poles' height difference for each section of wire where the poles are of different heights \((1 ≤ C ≤ 100)\). The poles, of course, are in a certain sequence and can not be moved.

Farmer John figures that if he makes some poles taller he can reduce his penalties, though with some other additional cost. He can add an integer X number of meters to a pole at a cost of X2.

Help Farmer John determine the cheapest combination of growing pole heights and connecting wire so that the cows can get their new and improved service.

给出若干棵树的高度,你可以进行一种操作:把某棵树增高 \(h\),花费为\(h\times h\)。

操作完成后连线,两棵树间花费为高度差 \(\times\) 定值 \(c\)。

求两种花费加和最小值。

输入格式

* Line 1: Two space-separated integers: \(N\) and \(C\)

* Lines 2..\(N+1\): Line \(i+1\) contains a single integer: heighti

输出格式

* Line 1: The minimum total amount of money that it will cost Farmer John to attach the new telephone wire.

样例输入

5 2
2
3
5
1
4

样例输出

15

暴力肯定是写不得的,直接考虑如何优化,状态 \(dp[i][j]\) 表示第 \(i\) 棵树 高度为 \(j\) 时的最小花费,我们能写出来这个式子,原因高度的范围非常小,我们肯定有一层循环来暴力枚举所有高度,外层枚举 \(i\) 我们不好下手。

仔细观察高度有一个很好的性质可以利用: 我们枚举的所有树的高度肯定是单调不减的。

考虑维护一个指针暴力转移,复杂度很好看\(O(nh)\) 。

Code.

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int n,c,h[N],dp[N][110],maxx,res=INT_MAX;
int main()
{
	scanf("%d%d",&n,&c);
	for(int i=1;i<=n;i++) scanf("%d",&h[i]),maxx=max(maxx,h[i]);
	for(int i=h[1];i<=maxx;i++)
		dp[1][i]=(i-h[1])*(i-h[1]);
	for(int i=2;i<=n;i++)
	{
		int x=h[i-1];
		for(int j=h[i];j<=maxx;j++)
		{
			while(dp[i-1][x]+abs(j-x)*c > dp[i-1][x+1]+ abs(j-x-1)*c&& x<maxx) x++;
			dp[i][j]=dp[i-1][x]+abs(j-x)*c+(j-h[i])*(j-h[i]);
		}
	}
	for(int i=h[n];i<=maxx;i++) res=min(res,dp[n][i]);
	printf("%d",res);
	return 0;
}

标签:Wire,cost,题解,Telephone,wire,poles,Farmer,new,John
来源: https://www.cnblogs.com/EastPorridge/p/16387399.html