codeforces 463B Caisa and Pylons 解题报告

题目链接:http://codeforces.com/problemset/problem/463/B

题目意思:Caisa 站在 0 pylon 并且只有 0 energy,他需要依次跳过1 pylon、2 pylon,...直到最后的 n pylon,每个 pylon(第 i 个) 都有对应的 height 值 hi,而每当从第 i 个pylon 跳到第i+1个pylon的时候,energy会增加 hi-hi+1,当然这个增加值有可能是负数,此时的energy则会相应的减少,现在要确保 energy 在任何时刻都是一个非负数。Caisa 可以向任意的一个pylon 增加 height,每增加一个单元的 height就需要 1 dollar,问从第1个 pylon 跳到 第 n 个pylon,且energy 是 非负的情况下,需要的最少dollar是多少。

    方法一:直接做,二分模拟(31ms)

    

 1 // 二分
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cstdlib>
 5 using namespace std;
 6 
 7 const int maxn = 1e5 + 2;
 8 int h[maxn], n;
 9 
10 bool check(int x)
11 {
12     if (x - h[0] < 0)
13         return false;
14     int energy = x - h[0];
15     for (int i = 0; i < n-1; i++)
16     {
17         energy += h[i] - h[i+1];
18         if (energy < 0)
19             return false;
20     }
21     return true;
22 }
23 
24 int main()
25 {
26     while (scanf("%d", &n) != EOF)
27     {
28         for (int i = 0; i < n; i++)
29             scanf("%d", &h[i]);
30         int l = 1, r = maxn;
31         int ans = maxn;
32         while (l <= r)
33         {
34             int m = (l+r)>>1;
35             if (check(m))
36             {
37                 ans = min(ans, m);
38                 r = m - 1;
39             }
40             else
41                 l = m + 1;
42         }
43         printf("%d\n", ans);
44     }
45     return 0;
46 }
View Code

 

    方法二:

    找出序列中的最大值即为答案(46ms,有点奇怪)。

    因为任意一个pylon 和 这个最大值的差都为正数或者0(序列中有多个最大值),也就是energy 一定不会变为负数!!!次大值也是不行的,因为如果序列中 pylon 1 的值是负数,energy 就为负数了,不符合条件。

    

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     int n, h;
10     while (scanf("%d", &n) != EOF)
11     {
12         int ans = 0;
13         for (int i = 0; i < n; i++)
14         {
15             scanf("%d", &h);
16             ans = max(ans, h);
17         }
18         printf("%d\n", ans);
19     }
20     return 0;
21 }
View Code

 

   

posted @ 2014-08-31 08:34  windysai  阅读(511)  评论(0编辑  收藏  举报