HackerRank# Candies

原题地址

 

LeetCode上也有这道题,直接扫一遍就行了,连数组都不用开,感觉像是蕴含了某种动归的思想在里面,要不怎么是个动归题呢

 

代码:

 1 #include <cmath>
 2 #include <cstdio>
 3 #include <vector>
 4 #include <iostream>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 int main() {
 9     /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
10     int n;
11     int curr_score, prev_score, curr_cnt;
12     int dir, len;
13     int res = 0;
14 
15     prev_score = -1;
16     curr_cnt = 0;
17     dir = 1;
18     scanf("%d", &n);
19     for (int i = 0; i < n; i++) {
20         scanf("%d", &curr_score);
21         if (curr_score > prev_score) {
22             if (dir < 0) {
23                 res += (1 - curr_cnt) * (len + (int) (curr_cnt <= 0));
24                 curr_cnt = 1;
25             }
26             curr_cnt += 1;
27             res += curr_cnt;
28             dir = 1;   
29         } else if (curr_score < prev_score) {
30             if (dir >= 0)
31                 len = 0;
32             curr_cnt -= 1;
33             res += curr_cnt;
34             dir = -1;
35             len += 1;
36         } else {
37             if (dir < 0)
38                 res += (1 - curr_cnt) * (len + (int) (curr_cnt <= 0));
39             curr_cnt = 1;
40             res += curr_cnt;
41             dir = 0;
42         }
43         prev_score = curr_score;
44     }
45     if (dir < 0)
46         res += (1 - curr_cnt) * (len + (int) (curr_cnt <= 0));
47 
48     cout << res << endl;
49     
50     return 0;
51 }

 

posted @ 2015-04-29 23:37  李舜阳  阅读(285)  评论(0编辑  收藏  举报