51nod 1285 Peaks and Segments

Topic source:  Codility
Base Time Limit: 1 second Space Limit: 131072 KB Score: 20Difficulty  : Level 3 Algorithm Questions
 collect
 focus on
Use an integer array A of length N that describes the heights of peaks and valleys. A mountain needs to satisfy the following conditions, 0 < P < N - 1 and A[P - 1] < A[P] > A[P + 1].
 
 
Take the above picture as an example, the height is: 1 5 3 4 3 4 1 2 3 4 6 2.
Now to divide the whole mountain into K sections, it is required that the number of points in each section is the same, and there is at least one mountain in each section, and how many sections can be divided into at most.
Input
Line 1: A number N representing the length of the array (1 <= N <= 50000).
Lines 2 - N + 1: 1 number Ai per line (1 <= Ai <= 10^9).
Output
Output how many segments the mountain can be divided into at most.
Input example
12
1
5
3
4
3
4
1
2
3
4
6
2
Output example
3. 

First find the factor of n. Since there are not many, you can calculate it all, and output whichever is larger.
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 5e4+10;
 4 int a[N], n, b[N];
 5 vector<int> vs;
 6 bool ok(int x) {
 7     if(b[n] < x) return false;
 8     int len = n/x;
 9     for(int i = 0; i < x; i ++) {
10         if(b[(i+1)*len]-b[i*len+1] == 0) return false;
11     }
12     return true;
13 }
14 int main() {
15     cin >> n;
16     for(int i = 1; i <= n; i ++) cin >> a[i];
17     for(int i = 2; i < n; i ++) {
18         b[i+1] = (a[i]>a[i-1]&&a[i]>a[i+1]) + b[i];
19     }
20     if(!b[n])return 0*printf("0\n");
21     // for(int i = 1; i<= n; i ++) printf("%d ",b[i] );printf("\n" );
22     for(int i = 2; i <= sqrt(n); i ++) {
23         if(n%i==0) {
24             vs.push_back(i);
25             vs.push_back(n/i);
26         }
27     }
28     sort(vs.begin(),vs.end());
29     for(int i = vs.size()-1; i >= 0; i --) {
30         if(ok(vs[i])) return 0*printf("%d\n",vs[i]);
31     }
32     printf("1\n");
33     return 0;
34 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325209851&siteId=291194637