先贴上我错误的代码:
#include <bits/stdc++.h>
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define debug(x) cout<<#x<<":"<<x<<endl;
#define f(i,a,n) for(int i=a;i<n;++i)
#define ff(i,a,n) for(int i=a;i<=n;++i)
#define OP freopen("D:\\Users\\HP ZBook15\\CLionProjects\\untitled\\demo\\in.TXT","r",stdin);
#define CL freopen("D:\\Users\\HP ZBook15\\CLionProjects\\untitled\\demo\\out.TXT","w",stdout);
const int INF=0x3f3f3f3f;
using namespace std;
typedef long long ll;
typedef double dbl;
typedef pair<int, int> pi;
//
int n;
void solve(){
cin>>n;
string s;
cin>>s;
int flag=0,p=0;
for(int i=n-1;i>=n/2;i--){
if(s[i]=='0'){
flag=i;
break;
}
}
if(flag){
cout<<1<<" "<<flag+1<<" "<<1<<" "<<flag<<endl;
}
else{
cout<<n/2<<" "<<n-1<<" "<<n/2+1<<" "<<n<<endl;
}
}
int main(){
multiCase solve();
return 0;
}
错误原因:
在else
里面判断失误,错误样例
2
4
1011
5
10111
我的错解:
2 3 3 4
2 4 3 5
正解1:
1 2 2 3
1 2 2 3
正解2:
2 4 3 4
2 5 3 5
解释:
当后一半(n为奇数的时候后一半多一个元素)没有0的时候,要用到前面一个数字去构造,如果前面一个是1,那么可以用,如果前面的不是1,那么就不能用这个数字了,下面两个代码看个人 思维习惯 理解吧
ac代码:
一种思维习惯:
#include <bits/stdc++.h>
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define debug(x) cout<<#x<<":"<<x<<endl;
#define f(i,a,n) for(int i=a;i<n;++i)
#define ff(i,a,n) for(int i=a;i<=n;++i)
#define OP freopen("D:\\Users\\HP ZBook15\\CLionProjects\\untitled\\demo\\in.TXT","r",stdin);
#define CL freopen("D:\\Users\\HP ZBook15\\CLionProjects\\untitled\\demo\\out.TXT","w",stdout);
const int INF=0x3f3f3f3f;
using namespace std;
typedef long long ll;
typedef double dbl;
typedef pair<int, int> pi;
//
int n;
void solve(){
cin>>n;
string s;
cin>>s;
int flag=0,p=0;
for(int i=n-1;i>=n/2;i--){
if(s[i]=='0'){
flag=i;
break;
}
}
if(flag) cout<<1<<" "<<flag+1<<" "<<1<<" "<<flag<<endl;
else cout<<n/2<<" "<<(s[n/2-1]=='1'?n-1:n)<<" "<<n/2+1<<" "<<n<<endl;
}
int main(){
multiCase solve();
return 0;
}
/*
4
4
1011
5
10111
4
1111
5
11111
*/
另一种思维习惯:
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
string s;
cin >> s;
for (int i = 0; i < n; i++) {
if (s[i] == '0') {
if (i < n / 2) {
cout << i + 1 << " " << n << " " << i + 2 << " " << n << "\n";
} else {
cout << 1 << " " << i + 1 << " " << 1 << " " << i << "\n";
}
return;
}
}
cout << 1 << " " << n / 2 * 2 << " " << 1 << " " << n / 2 << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}