cf1562D Two Hundred Twenty One
题意:
定义一个前缀和公式:a1−a2+a3−a4+..=∑i=1n(−1)i−1∗aia_{1}-a_{2}+a_{3}-a_{4}+..=\sum_{i=1}^{n}(-1)^{i-1}*a_{i}a1−a2+a3−a4+..=∑i=1n(−1)i−1∗ai
然后给你一个长度为n的序列,只包含{-1,1}。
然后q次询问,每次询问一个区间,问最少删除区间内多少个数字可以使得区间[l,r]的区间和等于0
题解:
先看简单版本,只输出删除个数。
我们用sum[i]表示题目所给公式的前缀和,通过样例可以猜出一个结论(具体证明详见官方题解)
- 如果区间[l,r]的区间和等于0,删除个数为0
- 如果区间和不为0,区间长度为奇数,答案为1
- 如果区间和不为0,区间长度为偶数,答案为2(可以先删除第l个,然后区间长度变成奇数,就是第二个情况)
对于区间长度为奇数的,一定存在某个位置pos,l<=pos<=r,使得删除第pos位后,剩下的区间和为0,pos的前半部分等于后半部分,也就是满足:
sum[r]-sum[pos]=sum[pos-1]-sum[l-1]
移项:
sum[r]+sum[l-1]=sum[pos]+sum[pos-1]
根据sum[r]+sum[l-1]的值去二分找sum[pos]+sum[pos-1]
存下sum[r]+sum[l-1]所对应的所有sum[pos]+sum[pos-1],方便二分去找
代码:
// Problem: D1. Two Hundred Twenty One (easy version)
// Contest: Codeforces - Codeforces Round #741 (Div. 2)
// URL: https://codeforces.com/contest/1562/problem/D1
// Memory Limit: 512 MB
// Time Limit: 2000 ms
// Data:2021-09-03 17:12:18
// By Jozky#include <bits/stdc++.h>
#include <unordered_map>
#define debug(a, b) printf("%s = %d\n", a, b);
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
clock_t startTime, endTime;
//Fe~Jozky
const ll INF_ll= 1e18;
const int INF_int= 0x3f3f3f3f;
void read(){};
template <typename _Tp, typename... _Tps> void read(_Tp& x, _Tps&... Ar)
{x= 0;char c= getchar();bool flag= 0;while (c < '0' || c > '9')flag|= (c == '-'), c= getchar();while (c >= '0' && c <= '9')x= (x << 3) + (x << 1) + (c ^ 48), c= getchar();if (flag)x= -x;read(Ar...);
}
template <typename T> inline void write(T x)
{if (x < 0) {x= ~(x - 1);putchar('-');}if (x > 9)write(x / 10);putchar(x % 10 + '0');
}
void rd_test()
{
#ifdef LOCALstartTime= clock();freopen("in.txt", "r", stdin);
#endif
}
void Time_test()
{
#ifdef LOCALendTime= clock();printf("\nRun Time:%lfs\n", (double)(endTime - startTime) / CLOCKS_PER_SEC);
#endif
}
const int maxn= 3e6 + 8;
int sum[maxn];
vector<int> vec[maxn];
int len, q;
int pos(int l, int r)
{int Sum= sum[r] + sum[l - 1] + 2 * len;int Pos= lower_bound(vec[Sum].begin(), vec[Sum].end(), l) - vec[Sum].begin();return vec[Sum][Pos];
}
int main()
{//rd_test();int t;read(t);while (t--) {read(len, q);string s;cin >> s;for (int i= 0; i < s.length(); i++) {if ((i + 1) % 2 == 0)sum[i + 1]= sum[i] + (s[i] == '+' ? -1 : 1);elsesum[i + 1]= sum[i] + (s[i] == '+' ? 1 : -1);}for (int i= 1; i <= len; i++) {int Sum= sum[i] + sum[i - 1];vec[Sum + 2 * len].push_back(i); //2*len是偏移量}while (q--) {int l, r;read(l, r);if (sum[r] - sum[l - 1] == 0)printf("0\n");else if ((r - l + 1) % 2 == 1) {printf("1\n");printf("%d\n", pos(l, r));}else {printf("2\n");printf("%d %d\n", l, pos(l + 1, r));}}for (int i= 1; i <= len; i++) {int Sum= sum[i] + sum[i - 1];vec[Sum + 2 * len].clear();}}return 0;//Time_test();
}