Codeforces Round #784 (Div. 4), problem: (C) Odd/Even Increments
直接将flag写到循环中,简化代码量
前一种解决方案
#include<iostream>
#include<cstring>
using namespace std;
const int N = 2e5+5;
int a[N];
int main(){
int T;
cin >> T;
while(T--){
memset(a,0,sizeof a);
int n;
cin >> n;
for(int i = 1; i <= n; i++){
cin >> a[i];
}
int flag = a[1]%2,wa = 0;;
for(int i = 3; i <= n; i+=2){
if(a[i]%2 != flag) wa = 1;
}
if(wa){
puts("NO");
continue;
}
flag = a[2]%2,wa = 0;;
for(int i = 4; i <= n; i += 2){
if(a[i]%2 != flag) wa = 1;
}
if(wa){
puts("NO");
}
else{
puts("YES");
}
}
}
后一种解决方案
#include<iostream>
#include<cstring>
using namespace std;
const int N = 110;
int a[N];
int main(){
int T;
cin >> T;
while(T--){
int n;
cin >> n;
// memset(a,0,sizeof a);
for(int i = 1; i <= n; i++){
cin >> a[i];
}
bool ok = true;
for(int i = 3; i <= n && ok; i += 2){
if(a[i]%2 != a[1]%2) ok = false;
}
for(int i = 4; i <= n && ok; i += 2){
if(a[i]%2 != a[2]%2) ok = false;
}
if(!ok){
puts("NO");
}
else{
puts("YES");
}
}
return 0;
}
Codeforces Round #784 (Div. 4), problem: (D) Colorful Stamp
使用或运算来表示两种变量,避免对初始情况的讨论
我的解决方案:
#include<iostream>
#include<cstring>
using namespace std;
const int N = 2e5+5;
int a[N];
int main(){
int T;
cin >> T;
while(T--){
memset(a,0,sizeof a);
int n;
cin >> n;
string s;
cin >> s;
int flag = 1,b_flag = 0,r_flag = 0;
for(int i = 0; i <= n; i++){
if((s[i] == 'W' && i != 0) || i == n){
if(b_flag == 0 && r_flag == 0) continue;
if(b_flag == 0 || r_flag == 0) flag = 0;
b_flag = 0,r_flag = 0;
}
if(s[i] == 'B') b_flag = 1;
if(s[i] == 'R') r_flag = 1;
}
if(flag) puts("YES");
else puts("NO");
}
return 0;
}
更简洁的解决方案:
#include<iostream>
#include<cstring>
using namespace std;
const int N = 2e5+5;
int a[N];
int main(){
int T;
cin >> T;
while(T--){
memset(a,0,sizeof a);
int n;
cin >> n;
string str;
cin >> str;
int s = 0,ok = 1;
for(int i = 0; i <= n && ok; i++){
if(str[i] == 'W' || i == n){
if(s == 1 || s == 2) ok = 0;
s = 0;
}
if(str[i] == 'B') s |= 1;
if(str[i] == 'R') s |= 2;
}
if(ok) puts("YES");
else puts("NO");
}
return 0;
}
还有一点就是表达两种条件只能有一种成立
(表达式1)+(表达式2) == 1