AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
int n;
string s;
cin >> n >> s;
int cnt = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '|') cnt++;
else if (cnt==0 && s[i] == '*') {
cout << "out" << endl;
return 0;
}
else if (cnt==1 && s[i] == '*') {
cout << "in" << endl;
return 0;
}
else if (cnt == 2) {
cout << "out" << endl;
return 0;
}
}
return 0;
}
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 200010;
int color;
struct Node {
int c, r;
int idx;
bool operator<(const Node& W)const {
return r > W.r;
}
}q[N];
int main()
{
int n,t;
cin >> n >> t;
for (int i = 1; i <= n; i++) {
cin >> q[i].c;
q[i].idx = i;
}
for (int i = 1; i <= n; i++) cin >> q[i].r;
/*for (int i = 1; i <= n; i++) {
cout << q[i].c << " " << q[i].r << " " << q[i].idx;
cout << endl;
}*/
color = q[1].c;
sort(q + 1, q + 1 + n);
for (int i = 1; i <= n; i++) {
if (q[i].c == t) {
cout << q[i].idx << endl;
return 0;
}
}
for (int i = 1; i <= n; i++) {
if (q[i].c == color) {
cout << q[i].idx << endl;
return 0;
}
}
return 0;
}
超时代码:
我一开始用双指针做,i来找到第一个o的位置,j来找到最后一个o的后一个位置,然后如果s[i-1]为-或者s[j]为-,那么res=max(res,j-i)
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 200010;
char s[N];
int main()
{
int n;
cin >> n;
cin >> s;
int res = -1;
for (int i = 0; i < n; i++) {
if (s[i] == 'o') {
int j = i;
while (j < n && s[j] == 'o') j++;
if (s[i - 1] == '-' || s[j] == '-') res = max(res, j - i);
}
}
cout << res << endl;
return 0;
}
需要进行一个优化,其实j根本就没必要回溯,只要一直往前走就行了,只有当j<i时,使得j从i开始出发就行了
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string.h>
using namespace std;
const int N = 200010;
char s[N];
int main()
{
int n;
cin >> n;
cin >> s;
int res = -1;
int j = 0;
for (int i = 0; i < n; i++) {
if (j < i) j = i;
if (s[i] == 'o') {
while (j < n && s[j] == 'o') j++;
if (s[i - 1] == '-' || s[j] == '-') res = max(res, j - i);
}
}
cout << res << endl;
return 0;
}
因为最左边是0,最右边是1,所以一定存在01,不一定存在10,要想找到一个位置p使得sp!=sp+1,只需要找到01的0位置就行
一直二分,长度为2的时候找到的就是01,l就是0的位置,r就是1的位置
用二分,在l到r-1二分(不需要l==r时才结束,只要l==r-1时就可以结束了,只要找到0的位置就行了)
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
int main() {
int n;
cin >> n;
int l = 1, r = n;
while (l < r-1) {
int mid = (l + r) / 2;
cout << "? " << mid << endl;
char ch;
cin >> ch;
if (ch== '0') l = mid;
else if (ch == '1') r = mid;
}
cout << "! " << l << endl;
return 0;
}