fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. typedef long double ld;
  5. typedef long long ll;
  6. typedef unsigned long long ull;
  7. const ll MAXN = 123456;
  8.  
  9. void pre();
  10. void post();
  11. ll n;
  12. string s;
  13.  
  14. void read()
  15. {
  16. cin >> n;
  17. cin >> s;
  18. }
  19.  
  20. int main()
  21. {
  22. pre();
  23. read();
  24. ll maxans;
  25. ll nowans;
  26. bool now;
  27. // if from 0 start
  28. now = true;
  29. nowans=0;
  30. for(int i=0;i<n;i++)
  31. {
  32. if(now) {if(s[i]=='0'){now = !now;nowans++;}}
  33. else {if(s[i]=='1'){now = !now;nowans++;}}
  34. }
  35. maxans = nowans;
  36. // if from 1 start
  37. now = false;
  38. nowans=0;
  39. for(int i=0;i<n;i++)
  40. {
  41. if(now) {if(s[i]=='0'){now = !now;nowans++;}}
  42. else {if(s[i]=='1'){now = !now;nowans++;}}
  43. }
  44. maxans = max(maxans,nowans);
  45.  
  46. vector<ll> blocks;
  47. bool flag = s[0]=='0'?false:true;
  48. bool startflag = flag;
  49. blocks.push_back(0);
  50. for(int i=0;i<n;i++)
  51. {
  52. if(flag && s[i]=='1')blocks[blocks.size()-1]++;
  53. else if(!flag && s[i]=='0')blocks[blocks.size()-1]++;
  54. else {flag = !flag;blocks.push_back(1);}
  55. }
  56. ll cntbolshe2=0;
  57. for(int i=0;i<blocks.size();i++)
  58. {
  59. if(blocks[i]>=2)cntbolshe2++;
  60. }
  61. if(cntbolshe2>=2)
  62. {
  63. cout << maxans+2;
  64. return 0;
  65. }
  66. for(int i=0;i<blocks.size();i++)
  67. {
  68. if(i<blocks.size()-1)
  69. if(blocks[i]>=2 && blocks[i+1]>=2)
  70. {
  71. cout << maxans+2;
  72. return 0;
  73. }
  74. if(i<blocks.size()-2)
  75. if(blocks[i]>=2 && blocks[i+2]>=2)
  76. {
  77. cout << maxans+2;
  78. return 0;
  79. }
  80. if(blocks[i]>=3)
  81. {
  82. cout << maxans+2;
  83. return 0;
  84. }
  85. }
  86. for(int i=0;i<blocks.size();i++)
  87. {
  88. if(blocks[i]>=2)
  89. {
  90. cout << maxans+1;
  91. return 0;
  92. }
  93. }
  94. cout << maxans;
  95. /*if(s.find("0011")!=string::npos)
  96.   {
  97.   cout << maxans+2;
  98.   }
  99.   else if(s.find("011")!=string::npos || s.find("001")!=string::npos ||
  100.   s.find("111")!=string::npos || s.find("000")!=string::npos)
  101.   {
  102.   cout << maxans+1;
  103.   }
  104.   else cout << maxans;*/
  105. post();
  106. return 0;
  107. }
  108.  
  109.  
  110. void pre()
  111. {
  112. #ifdef DEBUG
  113. freopen("input.txt", "r", stdin);
  114. freopen("output.txt", "w", stdout);
  115. #endif
  116. }
  117.  
  118. void post()
  119. {
  120. #ifdef DEBUG
  121. cerr << "Execution time: " << (ld) clock() / CLOCKS_PER_SEC;
  122. #endif
  123. }
Success #stdin #stdout 0s 3420KB
stdin
2
11
stdout
2