USACO Section1.3 Ski Course Design 解题报告

    skidesign解题报告 —— icedream61 博客园(转载请注明出处)
------------------------------------------------------------------------------------------------------------------------------------------------
【题目】
  N座山,每座山高度是0到100的整数。我们要调整山高,让最高的山和最低的山高度差不超过17。
  将一座山的高度调整x,花费是x²。注意,本题只允许山高改变整数值。
【数据范围】
  1<=N<=1000
【输入样例】
  5
  20
  4
  1
  24
  21
【输出样例】
  18
------------------------------------------------------------------------------------------------------------------------------------------------
【分析】
  这道题,关键在于想到怎么做,之后就毫无难度了。
  让山高的最大值与最小值差不大于17。如果你想着如何去逐步调整,那就复杂了,很难搞。
  但其实,可以换个思路,一步到位:将所有山高都调整到[l,r]的范围内,其中l+17==r。这很容易,只要将[0,l-1]的山变成l,[r+1,100]的山变成r即可,时间是线性的。而[l,r]的所有情况一共是大约100-17组,也是线性的。如此,便可在O(N²)内解决问题,其中N≈100-17。
------------------------------------------------------------------------------------------------------------------------------------------------
【总结】
  一遍AC。

------------------------------------------------------------------------------------------------------------------------------------------------

【代码】

 1 /*
 2 ID: icedrea1
 3 PROB: skidesign
 4 LANG: C++
 5 */
 6 
 7 #include <iostream>
 8 #include <fstream>
 9 using namespace std;
10 
11 const int maxInt = (1<<31)-1;
12 
13 int n,d[101];
14 
15 int js(int l,int r)
16 {
17     int cost=0;
18     for(int i=0;i<=l;++i) cost+=(l-i)*(l-i)*d[i];
19     for(int j=r;j<=100;++j) cost+=(j-r)*(j-r)*d[j];
20     return cost;
21 }
22 
23 void change(int &r,int x) { if(x<r) r=x; }
24 
25 int main()
26 {
27     ifstream in("skidesign.in");
28     ofstream out("skidesign.out");
29 
30     in>>n;
31     for(int i=1,x;i<=n;++i) { in>>x; ++d[x]; }
32 
33     int cost=maxInt;
34     for(int l=0,r;l<=100-17;++l)
35     {
36         r=l+17;
37         change(cost,js(l,r));
38     }
39     out<<cost<<endl;
40 
41     in.close();
42     out.close();
43     return 0;
44 }

 

posted on 2015-03-09 12:47  IceDream61  阅读(335)  评论(0编辑  收藏  举报

导航