#C++初学记录(算法考试1)
B - Maximal Continuous Rest
Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,an (each ai is either 0 or 1), where ai=0 if Polycarp works during the i-th hour of the day and ai=1 if Polycarp rests during the i-th hour of the day.
Days go one after another endlessly and Polycarp uses the same schedule for each day.
What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.
Input
The first line contains n (1≤n≤2⋅105) — number of hours per day.
The second line contains n integer numbers a1,a2,…,an (0≤ai≤1), where ai=0 if the i-th hour in a day is working and ai=1 if the i-th hour is resting. It is guaranteed that ai=0 for at least one i.
Output
Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.
Examples
Input
5
1 0 1 0 1
Output
2
Input
6
0 1 0 1 1 0
Output
2
Input
7
1 0 1 1 1 0 1
Output
3
Input
3
0 0 0
Output
0
正确代码
#include<bits/stdc++.h> using namespace std; const int MM = 2e5+5; int a[MM]; int main() { int n, res = 0, maxx = 0; cin >> n; for(int i = 1; i <= n; i++) { cin >> a[i]; if(a[i] == 1) { res++; if(i == n && maxx < res) { //if(maxx < res) //{ maxx = res; res = 0; // } } } else { if(maxx < res) { maxx = res; } res = 0; } } int res1 = 0, res2 = 0; for(int i = 1; i <= n; i++) { if(a[i] == 1) res1++; else break; } for(int i = n; i >= 1; i--) { if(a[i] == 1) res2++; else break; } int tt = 0; if(res1 != n) tt = res1+res2; //cout << maxx << endl; printf("%d\n", tt > maxx? tt:maxx); return 0; }
代码理解
该题不难,主要目的是判断1的连续个数,主要难点是如何判断开头和结尾1连续的个数,如果想到在两边同时进行判断则可以很迅速的编写完成代码,首先用if语句判断1的连续性,即用数组a进行储存1和0,若a[i]==1则进行下一个循环,若a[i]!=1即a[i]==0则跳出循环,与此同时进行两边同时判断1的连续性函数,即从开始a[0]判断1连续的个数,若a[i]==0则结束循环进行从后向前判断a[n-1]是否等于零,判断出前后连续1的个数则进行相加即代码中的res1+res2,最后用最大值max和res1+res2比较大小,最后输出最大的那一项。
- 点赞
- 收藏
- 分享
- 文章举报
- #C++初学记录(算法测试2019/5/5)(深度搜索)
- #C++初学记录(算法效率与度量)
- #C++初学记录#日常学习函数
- #C++初学记录(遍历)
- #初学c++笔记心得记录
- 算法学习记录十三(C++)--->10年微软面试题树的子结构
- #C++初学记录(字符串与指针操作库函数)
- 算法学习记录五(C++)--->两个栈实现队列
- #C++初学记录(奶酪#并查集)
- #C++初学记录(贪心算法#二分查找)
- 算法学习记录一(C++)--->二维数组中的查找
- 数据结构、算法与应用(C++描述)阅读记录
- #C++初学记录(动态规划 被3整除的子序列)
- #C++初学记录(acm试题#预处理)
- #C++初学记录(set进阶#acm cf 190802 B. Subsegments)
- 算法学习记录十二(C++)--->链表题目集合
- 算法学习记录八(C++)--->一句代码搞定变态跳台阶
- #C++初学记录(ACM8-6-cf-f题)
- 算法学习记录六(C++)--->获取斐波那契数列第n项
- 初学C++基本知识记录