MT45. 最长全1串
描述
输入描述
输入第一行两个整数 n , k ,表示字符串长度和机会次数输出描述
输出一行表示答案示例1
输入:
10 2 1 0 0 1 0 1 0 1 0 1
输出:
5
示例2
输入:
10 5 1 0 0 1 0 1 0 1 0 1
输出:
10
C++ 解法, 执行用时: 6ms, 内存消耗: 3648KB, 提交时间: 2020-07-28
#include <bits/stdc++.h> using namespace std; #define gc() (p1==p2&&(p1=bf,p2=bf+fread(bf,1,1<<24,stdin),p1==p2)?EOF:*p1++) char bf[1<<24], *p1=bf, *p2=bf; template<class T> void read(T& x) { char c(gc()); T t(0); for (; c != EOF && !isdigit(c); c = gc()); for (; isdigit(c); c = gc()) t = 10 * t + (c & 15); x = t; } int main() { int n,k,x,c(0); vector<int> vv; read(n); read(k); for(int i =0;i<n;++i){ read(x); if(!x){ vv.push_back(i); c++; } } vv.push_back(n); if(c<k)k = c; int ans = vv[k]; for(int i = k + 1;i<vv.size();++i){ ans = max(ans,vv[i] - vv[i-k-1] - 1); } cout<<ans<<endl; }
C++14 解法, 执行用时: 7ms, 内存消耗: 3160KB, 提交时间: 2020-05-20
#include <bits/stdc++.h> using namespace std; #define gc() (p1==p2&&(p1=bf,p2=bf+fread(bf,1,1<<24,stdin),p1==p2)?EOF:*p1++) char bf[1<<24], *p1=bf, *p2=bf; template<class T> void read(T& x) { char c(gc()); T t(0); for (; c != EOF && !isdigit(c); c = gc()); for (; isdigit(c); c = gc()) t = 10 * t + (c & 15); x = t; } int main() { int n,k,x,c(0); vector<int> vv; read(n); read(k); for(int i =0;i<n;++i){ read(x); if(!x){ vv.push_back(i); c++; } } vv.push_back(n); if(c<k)k = c; int ans = vv[k]; for(int i = k + 1;i<vv.size();++i){ ans = max(ans,vv[i] - vv[i-k-1] - 1); } cout<<ans<<endl; }