Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3198 | Accepted: 1119 |
Description
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 utilizeN (2 ≤ N ≤ 100,000) already-installed telephone poles, each with someheighti meters (1 ≤ heighti ≤ 100). The new wire will connect the tops of each pair of adjacent poles and will incur a penalty costC × 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 integerX 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.
Input
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains a single integer: heighti
Output
* Line 1: The minimum total amount of money that it will cost Farmer John to attach the new telephone wire.
Sample Input
5 2 2 3 5 1 4
Sample Output
2
6
题意:给出n根电线杆的高度和参数c, 要搭电线,相邻两根电线杆的话费为|h[i]-h[i+1]|*c, 也可以把杆加高,加高x的花费为x*x......问最小花费?
此题DP, 开始已经推出了公式:f[i][j] = (j-rh[i])*(j-rh[i]) + f[i-1][k] + c*abs(j-k)
然后就不会优化了,效率n*T*T.......TLETLE
据说啊,把这个递推式拆一下。。。
f[i][j] = (j-rh[i])*(j-rh[i]) + c*j + min{(f[i-1][k]-c*k))} (j <= k)或
f[i][j] = (j-rh[i])*(j-rh[i]) -c*j + min{(f[i-1][k]+c*k))} (j > k)
那么后半部分就可以用一个循环算了,算法比较神奇。。。
low[j] = min{f[i-1][j]+c*j};
high[j] = min{f[i-1][j]-c*j};
则新的方程为f[i][j] = (j-rh[i])*(j-rh[i]) + min(low[j]-c*j, high[j]+c*j);
<pre name="code" class="cpp">#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define MAXN (100000+5)
#define MAXT (100+5)
int f[MAXN][MAXT], rh[MAXN], low[MAXT], high[MAXT];
int main(){
freopen("telewire.in", "r", stdin);
freopen("telewire.out", "w", stdout);
int n, c, maxh = 0;
scanf("%d%d", &n, &c);
for(int i = 1; i <= n; i++) scanf("%d", &rh[i]), maxh = max(maxh, rh[i]);
for(int i = 1; i <= 100; i++) f[0][i] = 0;
// rh[0] = maxh;
for(int i = 1; i <= n; i++){
int j, t = INF;
for(t=INF, j = maxh; j; j--) low[j] = t = min(t, f[i-1][j]+j*c);
for(t=INF, j = 1; j <= maxh; j++) high[j] = t = min(t, f[i-1][j]-j*c), f[i][j] = INF;
for(j = rh[i]; j <= maxh; j++)
f[i][j] = (j-rh[i])*(j-rh[i]) + min(high[j]+j*c,low[j]-j*c);
}
int ans = INF;
for(int j = rh[n]; j <= maxh; j++) ans = min(ans, f[n][j]);
printf("%d\n", ans);
return 0;
}