Telephone Wire(POJ-3612)
Problem 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 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.
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
15
題意:要改造n個(gè)電線桿,相鄰兩電線桿改造費(fèi)用=C*兩電線桿的高度差,也可對(duì)任意電線桿進(jìn)行加長x,但要花費(fèi)加長費(fèi)用x^2,求改造電線桿的最少的費(fèi)用。
思路
用f[i][j]表示第i棵樹高度為j的時(shí)候的最小代價(jià),枚舉相鄰兩棵樹高度即可,狀態(tài)方程:f[i][j]=min(f[i][k]+abs(j-k)+(j-a[i])^2),測試后發(fā)現(xiàn)超時(shí),不知道怎么優(yōu)化,看了他人題解。
對(duì)狀態(tài)方程進(jìn)行優(yōu)化,利用分類討論j<k和j>=k,將k維度用兩個(gè)數(shù)組預(yù)處理,即:high[j]=min(f[i-1][k]-k*c) (j>=k),low[j]=min(f[i-1][k]+k*c) (j<k),原狀態(tài)方程就變?yōu)?#xff1a;f[i][j]=(j-a[i])^2+min(high[j]+j*c,low[j]-j*c);
Source Program
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<string> #include<cstdlib> #include<queue> #include<vector> #define INF 0x3f3f3f3f #define PI acos(-1.0) #define N 105 #define MOD 100001 #define E 1e-12 using namespace std; int low[N],high[N],f[N]; int main() {int n,m;while(scanf("%d%d",&n,&m)!=EOF){int a;scanf("%d",&a);for(int i=1;i<=100;i++){if(i<a)f[i]=INF;elsef[i]=(a-i)*(a-i);}for(int i=1;i<n;i++){int temp=INF;scanf("%d",&a);for(int j=100;j>0;j--)//對(duì)low預(yù)處理{temp=min(temp,f[j]+j*m);low[j]=temp;}for(int j=1;j<=100;j++)//對(duì)high預(yù)處理{temp=min(temp,f[j]-j*m);high[j]=temp;f[j]=INF;}for(int j=a;j<=100;j++)f[j]=(j-a)*(j-a)+min(low[j]-j*m,high[j]+j*m);}int ans=INF;for(int i=1;i<=100;i++)ans=min(ans,f[i]);printf("%d\n",ans);} }?
總結(jié)
以上是生活随笔為你收集整理的Telephone Wire(POJ-3612)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 搜索 —— 广搜的优化技巧
- 下一篇: 亲戚(信息学奥赛一本通-T1346)