红桃J

用心写好每行完美的代码,远比写一堆更有价值

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

无脑写代码代码(TLE):

 1 #include<iostream>
 2 #include<vector>
 3 
 4 using namespace std;
 5 
 6 int findLeft(int i, vector<int> height)
 7 {
 8     int t = i-1;
 9     while ((t+1<height.size())&&t >= 0)
10     {
11         if (height[t] > height[t + 1])
12             t--;
13         else
14             break;
15     }
16     return t + 1;
17 }
18 
19 int findRight(int i, vector<int> height)
20 {
21     int t = i + 1; 
22     while ((t-1>=0)&&t < height.size())
23     {
24         if (height[t] > height[t - 1])
25             t++;
26         else
27             break;
28     }
29     return t - 1;
30 }
31 
32 int trap(vector<int>& height) 
33 {
34     int L = height.size();
35     int sum = 0;
36     for (int i = 1; i < L-1; i++)
37     {
38         int left = findLeft(i, height);
39         int right = findRight(i, height);
40         if (left < i&&right > i)
41         {
42             int high = height[left] < height[right] ? height[left] : height[right];
43             for (int j = left+1; j < right; j++)
44             {
45                 sum = sum + high - height[j];
46             }
47         }
48     }
49     return sum;
50 }
51 
52 int main()
53 {
54     vector<int> height = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
55     cout << trap(height) << endl;
56 }
View Code

 

posted on 2015-05-16 16:41  红桃J  阅读(189)  评论(0编辑  收藏  举报