比赛记录 【Educational Codeforces Round 95】
Educational Codeforces Round 95
A. Buying Torches
制作
一次交换可以将木棍个数增加
My Code
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
void solve(void)
{
ll x,y,d;
scanf("%lld%lld%lld",&x,&y,&d);
printf("%lld\n",(d + y * d - 1 + x-1 - 1)/(x-1) + d);
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--) solve();
return 0;
}
B. Negative Prefixes
设
于是将所有未锁定的元素从大到小排序即可。
My Code
比赛的时候直接枚举了最后一个满足
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 1e2 + 5;
int a[MAXN], l[MAXN];
void solve(void)
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
for(int i=1; i<=n; ++i) scanf("%d",&l[i]);
for(int k=0; k<=n; ++k)
{
vector<int> b,c;
for(int i=1; i<=k; ++i)
if(!l[i]) b.push_back(a[i]);
for(int i=k+1; i<=n; ++i)
if(!l[i]) c.push_back(a[i]);
sort(b.begin(), b.end());
sort(c.begin(), c.end());
reverse(c.begin(), c.end());
for(int i=1,j=0,k=0; i<=n; ++i) if(!l[i])
{
if(j < (int)b.size()) a[i] = b[j++];
else a[i] = c[k++];
}
ll sum = 0;
bool mx = 0;
for(int i=1; i<=n; ++i)
{
sum += a[i];
if(sum < 0) mx = i;
}
if(mx <= k)
{
for(int i=1; i<=n; ++i)
printf("%d ",a[i]);
putchar('\n');
return;
}
}
putchar('\n');
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--) solve();
return 0;
}
下面是贪心的做法。
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int MAXN = 1e2 + 5;
int a[MAXN], l[MAXN];
void solve(void)
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
for(int i=1; i<=n; ++i) scanf("%d",&l[i]);
vector<int> b;
for(int i=1; i<=n; ++i)
if(!l[i]) b.push_back(a[i]);
sort(b.begin(),b.end());
reverse(b.begin(),b.end());
for(int i=1,j=0; i<=n; ++i)
printf("%d ",l[i]? a[i]: b[j++]);
putchar('\n');
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--) solve();
return 0;
}
Code
neal
将未锁定的数的下标进行排序。最后还原回去。
#include <algorithm>
#include <array>
#include <cassert>
#include <iostream>
#include <vector>
using namespace std;
template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; }
template<typename T, size_t size> ostream& operator<<(ostream &os, const array<T, size> &arr) { os << '{'; string sep; for (const auto &x : arr) os << sep << x, sep = ", "; return os << '}'; }
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
#ifdef NEAL_DEBUG
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif
template<typename T_vector>
void output_vector(const T_vector &v, bool add_one = false, int start = -1, int end = -1) {
if (start < 0) start = 0;
if (end < 0) end = int(v.size());
for (int i = start; i < end; i++)
cout << v[i] + (add_one ? 1 : 0) << (i < end - 1 ? ' ' : '\n');
}
void run_case() {
int N;
cin >> N;
vector<int> A(N);
for (auto &a : A)
cin >> a;
vector<int> L(N);
for (auto &l : L)
cin >> l;
vector<int> unlocked;
for (int i = 0; i < N; i++)
if (L[i] == 0)
unlocked.push_back(i);
vector<int> order = unlocked;
sort(order.begin(), order.end(), [&](int x, int y) {
return A[x] > A[y];
});
vector<int> B = A;
for (int i = 0; i < int(unlocked.size()); i++)
B[unlocked[i]] = A[order[i]];
output_vector(B);
}
int main() {
ios::sync_with_stdio(false);
#ifndef NEAL_DEBUG
cin.tie(nullptr);
#endif
int tests;
cin >> tests;
while (tests-- > 0)
run_case();
}
tourist
/**
* author: tourist
* created: 14.09.2020 20:09:38
**/
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<int> l(n);
for (int i = 0; i < n; i++) {
cin >> l[i];
}
vector<int> b;
for (int i = 0; i < n; i++) {
if (l[i] == 0) {
b.push_back(a[i]);
}
}
// a[1] a[2] a[3] a[4] ... a[n]
// p[i] = a[1] + a[2] + ... + a[i]
// i < j, a[i] < a[j]
// what happens to p[] if we swap(a[i], a[j])?
// p[1], p[2], ..., p[i-1] don't change
// p[i] increases by (a[j]-a[i])
// p[i+1] increases by (a[j]-a[i])
// ...
// p[j-1] increases by (a[j]-a[i])
// p[j], p[j+1], p[j+2], ..., p[n] don't change
sort(b.rbegin(), b.rend());
int j = 0;
for (int i = 0; i < n; i++) {
if (l[i] == 0) {
a[i] = b[j++];
}
}
for (int i = 0; i < n; i++) {
if (i > 0) {
cout << " ";
}
cout << a[i];
}
cout << '\n';
}
return 0;
}
C. Mortal Kombat Tower
dp
将 “我” 称为 A,“朋友” 称为 B。
设
边界条件是
转移时枚举当前的人跳了几步即可。注意当前操作的人是 A 的时候,转移无需额外代价。
My Code
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 2e5 + 5;
const int inf = 0x3f3f3f3f;
int a[MAXN];
void solve(void)
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
static int f[MAXN][2];
f[0][0] = 0; f[0][1] = inf;
for(int i=1; i<=n; ++i)
{
f[i][0] = i<2? f[i-1][1]: min(f[i-1][1], f[i-2][1]);
f[i][1] = i<2? f[i-1][0] + a[i]: min(f[i-1][0] + a[i], f[i-2][0] + a[i] + a[i-1]);
}
printf("%d\n",min(f[n][0], f[n][1]));
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--) solve();
return 0;
}
贪心
将 “我” 称为 A,“朋友” 称为 B。
首先,B 必须取第一个位置的数,于是我们直接将答案累加上这个代价,并且忽略掉这个位置,注意下面的讨论都是忽略掉了第一个位置。
考虑一段长度为
My Code
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 2e5 + 5;
const int inf = 0x3f3f3f3f;
int a[MAXN];
void solve(void)
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
static int f[MAXN][2];
f[0][0] = 0; f[0][1] = inf;
for(int i=1; i<=n; ++i)
{
f[i][0] = i<2? f[i-1][1]: min(f[i-1][1], f[i-2][1]);
f[i][1] = i<2? f[i-1][0] + a[i]: min(f[i-1][0] + a[i], f[i-2][0] + a[i] + a[i-1]);
}
printf("%d\n",min(f[n][0], f[n][1]));
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--) solve();
return 0;
}
Code
neal
使用了 fight 和 who 等使 dp 更加清晰。
#include <algorithm>
#include <array>
#include <cassert>
#include <iostream>
#include <vector>
using namespace std;
template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; }
template<typename T, size_t size> ostream& operator<<(ostream &os, const array<T, size> &arr) { os << '{'; string sep; for (const auto &x : arr) os << sep << x, sep = ", "; return os << '}'; }
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
#ifdef NEAL_DEBUG
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif
const int INF = 1e9 + 5;
void run_case() {
int N;
cin >> N;
vector<int> A(N);
for (auto &a : A)
cin >> a;
vector<array<int, 2>> dp(N + 1, {INF, INF});
dp[0][1] = 0;
for (int i = 0; i < N; i++)
for (int who = 0; who < 2; who++)
for (int fight = 1; fight <= min(N - i, 2); fight++) {
int hard = A[i] + (fight > 1 ? A[i + 1] : 0);
dp[i + fight][!who] = min(dp[i + fight][!who], dp[i][who] + who * hard);
}
cout << min(dp[N][0], dp[N][1]) << '\n';
}
int main() {
ios::sync_with_stdio(false);
#ifndef NEAL_DEBUG
cin.tie(nullptr);
#endif
int tests;
cin >> tests;
while (tests-- > 0)
run_case();
}
tourist
分成了两个数组 us 和 him 进行转移。
/**
* author: tourist
* created: 14.09.2020 20:21:16
**/
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
// him[i] -- the smallest # of skip points required to kill bosses [i; n) if it's our friend's turn to move
// us[i] -- ...... if it's our turn to move
vector<int> him(n + 1);
vector<int> us(n + 1);
him[n] = us[n] = 0;
for (int i = n - 1; i >= 0; i--) {
{ // calculate him[i]
him[i] = us[i + 1] + a[i];
if (i + 2 <= n) {
him[i] = min(him[i], us[i + 2] + a[i] + a[i + 1]);
}
}
{ // calculate us[i]
us[i] = him[i + 1];
if (i + 2 <= n) {
us[i] = min(us[i], him[i + 2]);
}
}
}
cout << him[0] << '\n';
}
return 0;
}
D. Trash Problem
方法 1
如果当前物品个数
设当前有
需要维护的东西有:
坐标从小到大排序后的结果可以用 set 来维护,下面称这个 set 为 mutiset 来维护所有相邻两个物品的距离,即维护所有 multiset 为
下面以插入物品为例,在
- 若
S 为空,直接插入。 - 否则:
- 若元素插入到集合的最开头或最末尾,设
S 中与它相邻的元素坐标为p ,那么在T 中插入|p-x| 即可。 - 否则,设它在
S 中的前后两个元素的坐标分别为p,q ,那么将q-p 从T 中删除,并且在T 中再插入x-p 和q-x 即可。
- 若元素插入到集合的最开头或最末尾,设
删除的过程类似,这里不再赘述。
My Code
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 1e5 + 5;
set<int> pos;
multiset<int> len;
inline void add_new(int p)
{
if(pos.empty())
{
pos.insert(p);
return;
}
set<int>::iterator it = pos.lower_bound(p);
if(it == pos.end())
{
len.insert(p - *pos.rbegin());
pos.insert(p);
return;
}
if(it == pos.begin())
{
len.insert(*it - p);
pos.insert(p);
return;
}
int nxt = *it, lst = *--it;
len.erase(len.lower_bound(nxt - lst));
len.insert(nxt - p);
len.insert(p - lst);
pos.insert(p);
}
inline void remove(int p)
{
pos.erase(p);
if(pos.empty()) return;
set<int>::iterator it = pos.lower_bound(p);
if(it == pos.end())
{
len.erase(len.lower_bound(p - *pos.rbegin()));
return;
}
if(it == pos.begin())
{
len.erase(len.lower_bound(*it - p));
return;
}
int nxt = *it, lst = *--it;
len.erase(len.lower_bound(nxt - p));
len.erase(len.lower_bound(p - lst));
len.insert(nxt - lst);
}
inline int query(void)
{
if((int)pos.size() <= 2) return 0;
return *pos.rbegin() - *pos.begin() - *len.rbegin();
}
int main(void)
{
int n,Q;
static int p[MAXN];
scanf("%d%d",&n,&Q);
for(int i=1; i<=n; ++i) scanf("%d",&p[i]);
sort(p+1,p+n+1);
for(int i=1; i<=n; ++i) pos.insert(p[i]);
for(int i=2; i<=n; ++i) len.insert(p[i] - p[i-1]);
printf("%d\n",query());
while(Q--)
{
int oper,x;
scanf("%d%d",&oper,&x);
if(oper == 0) remove(x);
else add_new(x);
printf("%d\n",query());
}
return 0;
}
方法 2
将修改离线,将所有坐标离散化。
考虑使用线段树维护。线段树上每个节点
- 该节点表示的区间中,两堆相邻垃圾的距离最大是多少,记为
res_u 。 - 该节点表示的区间中,坐标最大的垃圾的坐标,记为
mx_u 。 - 该节点表示的区间中,坐标最小的垃圾的坐标,记为
mn_u 。
特别地,如果
记 push_up 的时候,直接令
My Code
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int MAXN = 1e5 + 5;
const int MAXQ = 1e5 + 5;
const int MAXD = MAXN + MAXQ;
const int inf = 0x3f3f3f3f;
template<const int MAXN>
struct Segment_Tree
{
int n, mn[MAXN<<2], mx[MAXN<<2], res[MAXN<<2];
#define ls(u) ((u)<<1)
#define rs(u) ((u)<<1|1)
#define lson(u) ls(u),l,mid
#define rson(u) rs(u),mid+1,r
inline void push_up(int u)
{
mn[u] = min(mn[ls(u)], mn[rs(u)]);
mx[u] = max(mx[ls(u)], mx[rs(u)]);
res[u] = max(res[ls(u)], res[rs(u)]);
if(res[ls(u)] != -inf && res[rs(u)] != -inf)
res[u] = max(res[u], mn[rs(u)] - mx[ls(u)]);
}
inline void build(int n_){ n=n_; build(1,1,n);}
void build(int u,int l,int r)
{
mn[u]=inf; mx[u]=-inf; res[u]=-inf;
if(l==r) return;
int mid = (l+r)>>1;
build(lson(u)); build(rson(u));
}
inline void update_insert(int q,int k){ update_insert(1,1,n,q,k);}
void update_insert(int u,int l,int r,int q,int k)
{
if(l==r){ mn[u]=mx[u]=k; res[u]=0; return;}
int mid = (l+r)>>1;
if(q<=mid) update_insert(lson(u),q,k);
else update_insert(rson(u),q,k);
push_up(u);
}
inline void update_erase(int q){ update_erase(1,1,n,q);}
void update_erase(int u,int l,int r,int q)
{
if(l==r){ mn[u]=inf; mx[u]=-inf; res[u]=-inf; return;}
int mid = (l+r)>>1;
if(q<=mid) update_erase(lson(u),q);
else update_erase(rson(u),q);
push_up(u);
}
inline int query(void){ return res[1] == -inf? 0: mx[1] - mn[1] - res[1];}
};
struct Query
{
int oper,x;
}q[MAXQ];
int p[MAXN];
int dsc[MAXD], dcnt = 0;
int main(void)
{
int n,Q;
scanf("%d%d",&n,&Q);
for(int i=1; i<=n; ++i) scanf("%d",&p[i]);
for(int i=1; i<=Q; ++i) scanf("%d%d",&q[i].oper,&q[i].x);
for(int i=1; i<=n; ++i) dsc[++dcnt] = p[i];
for(int i=1; i<=Q; ++i) dsc[++dcnt] = q[i].x;
sort(dsc+1,dsc+dcnt+1);
dcnt = unique(dsc+1,dsc+dcnt+1) - dsc - 1;
for(int i=1; i<=n; ++i)
p[i] = lower_bound(dsc+1,dsc+dcnt+1, p[i]) - dsc;
for(int i=1; i<=Q; ++i)
q[i].x = lower_bound(dsc+1,dsc+dcnt+1, q[i].x) - dsc;
static Segment_Tree<MAXD> tree;
tree.build(dcnt);
for(int i=1; i<=n; ++i) tree.update_insert(p[i], dsc[p[i]]);
printf("%d\n",tree.query());
for(int i=1; i<=Q; ++i)
{
if(q[i].oper == 0) tree.update_erase(q[i].x);
else tree.update_insert(q[i].x, dsc[q[i].x]);
printf("%d\n",tree.query());
}
return 0;
}
Code
neal
#include <algorithm>
#include <array>
#include <cassert>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; }
template<typename T, size_t size> ostream& operator<<(ostream &os, const array<T, size> &arr) { os << '{'; string sep; for (const auto &x : arr) os << sep << x, sep = ", "; return os << '}'; }
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
#ifdef NEAL_DEBUG
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif
int main() {
ios::sync_with_stdio(false);
#ifndef NEAL_DEBUG
cin.tie(nullptr);
#endif
int N, Q;
cin >> N >> Q;
multiset<int> gaps;
set<int> positions;
auto &&add_position = [&](int p) {
auto it = positions.insert(p).first;
auto next_it = it;
next_it++;
if (next_it != positions.end())
gaps.insert(*next_it - p);
if (it != positions.begin()) {
auto prev_it = it;
prev_it--;
gaps.insert(p - *prev_it);
if (next_it != positions.end())
gaps.erase(gaps.find(*next_it - *prev_it));
}
};
auto &&erase_position = [&](int p) {
auto it = positions.find(p);
assert(it != positions.end());
auto next_it = it;
next_it++;
if (next_it != positions.end())
gaps.erase(gaps.find(*next_it - p));
if (it != positions.begin()) {
auto prev_it = it;
prev_it--;
gaps.erase(gaps.find(p - *prev_it));
if (next_it != positions.end())
gaps.insert(*next_it - *prev_it);
}
positions.erase(it);
};
auto &&query = [&] {
if (positions.size() <= 2)
return 0;
return *(--positions.end()) - *positions.begin() - *(--gaps.end());
};
for (int i = 0; i < N; i++) {
int p;
cin >> p;
add_position(p);
}
cout << query() << '\n';
for (int q = 0; q < Q; q++) {
int type, x;
cin >> type >> x;
if (type == 0)
erase_position(x);
else
add_position(x);
cout << query() << '\n';
}
}
tourist
/**
* author: tourist
* created: 14.09.2020 20:35:13
**/
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
// p[0] < p[1] < ... < p[n - 1]
// (suppose) we want to move all these piles into ONE point
// if in one move we could only move one pile:
// move everything to p[n / 2]
// if in one move we can move ALL piles from x to x+1 or x-1:
// we need exactly (p[n - 1] - p[0]) steps
// finally, if we want to move all piles into TWO points:
// we have to pick some border position, i
// now move p[0], p[1], ..., p[i - 1] into one point
// and p[i], p[i + 1], ..., p[n - 1] into another one
// and we'll need (p[i - 1] - p[0]) + (p[n - 1] - p[i]) steps
// == (p[n - 1] - p[0]) - (p[i] - p[i - 1])
int n, tt;
cin >> n >> tt;
set<int> p;
multiset<int> d; // the set of all differences: p[1] - p[0], p[2] - p[1], ...
auto Add = [&](int x) {
auto ret = p.insert(x);
assert(ret.second);
auto it = ret.first;
if (next(it) != p.end() && it != p.begin()) {
d.erase(d.find(*next(it) - *prev(it)));
}
if (next(it) != p.end()) {
d.insert(*next(it) - *it);
}
if (it != p.begin()) {
d.insert(*it - *prev(it));
}
};
auto Remove = [&](int x) {
auto it = p.find(x);
assert(it != p.end());
if (next(it) != p.end()) {
d.erase(d.find(*next(it) - *it));
}
if (it != p.begin()) {
d.erase(d.find(*it - *prev(it)));
}
if (next(it) != p.end() && it != p.begin()) {
d.insert(*next(it) - *prev(it));
}
p.erase(it);
};
for (int i = 0; i < n; i++) {
int foo;
cin >> foo;
Add(foo);
}
for (int qq = 0; qq <= tt; qq++) {
{
// == (p[n - 1] - p[0]) - (p[i] - p[i - 1])
if (d.empty()) {
cout << 0 << '\n';
} else {
int max_p = *prev(p.end());
int min_p = *p.begin();
int max_d = *prev(d.end());
cout << max_p - min_p - max_d << '\n';
}
}
if (qq == tt) {
break;
}
int t, x;
cin >> t >> x;
if (t == 0) {
Remove(x);
} else {
Add(x);
}
}
return 0;
}
oleh1421
使用了方法 2,即线段树。
#include <bits/stdc++.h>
typedef long long ll;
#define endl '\n'
using namespace std;
const ll mod=998244353ll;
const int N=200010;
int x[N];
int p[N];
map<int,int>mp;
struct node{
bool empt;
int mn,mx,res;
};
node t[N*4];
void build(int v,int l,int r){
if (l>r) return;
t[v].empt=true;
t[v].mn=t[v].mx=t[v].res=-1;
if (l==r) return;
int m=(l+r)/2;
build(v+v,l,m);
build(v+v+1,m+1,r);
}
node Merge(node A,node B){
if (A.empt) return B;
if (B.empt) return A;
node C;
C.empt=false;
C.mn=A.mn;
C.mx=B.mx;
C.res=max({A.res,B.res,B.mn-A.mx});
return C;
}
void upd(int v,int l,int r,int pos,int x){
if (l==r){
if (t[v].empt){
t[v].empt=false;
t[v].mn=t[v].mx=x;
t[v].res=0;
} else {
t[v].empt=true;
t[v].mn=t[v].mx=t[v].res=-1;
}
return;
}
int m=(l+r)/2;
if (pos<=m) upd(v+v,l,m,pos,x);
else upd(v+v+1,m+1,r,pos,x);
t[v]=Merge(t[v+v],t[v+v+1]);
}
int ans(){
if (t[1].empt) return 0;
return t[1].mx-t[1].mn-t[1].res;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int n,m;cin>>n>>m;
for (int i=1;i<=n;i++) cin>>p[i];
for (int i=1;i<=m;i++){
int t;cin>>t>>x[i];
}
set<int>st;
for (int i=1;i<=n;i++){
st.insert(p[i]);
}
for (int i=1;i<=m;i++){
st.insert(x[i]);
}
int k=0;
for (int i:st){
mp[i]=++k;
}
build(1,1,k);
for (int i=1;i<=n;i++){
// cout<<mp[p[i]]<<endl;
upd(1,1,k,mp[p[i]],p[i]);
// cout<<t[1].mn<<" "<<t[1].mx<<endl;
}
cout<<ans()<<endl;
for (int i=1;i<=m;i++){
upd(1,1,k,mp[x[i]],x[i]);
cout<<ans()<<endl;
}
return 0;
}
natsugiri
#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#else
#define NDEBUG
#define eprintf(...) do {} while (0)
#endif
#include<cassert>
using namespace std;
typedef long long LL;
typedef vector<int> VI;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define EACH(i,c) for(__typeof((c).begin()) i=(c).begin(),i##_end=(c).end();i!=i##_end;++i)
template<class T> inline void amin(T &x, const T &y) { if (y<x) x=y; }
template<class T> inline void amax(T &x, const T &y) { if (x<y) x=y; }
template<class Iter> void rprintf(const char *fmt, Iter begin, Iter end) {
for (bool sp=0; begin!=end; ++begin) { if (sp) putchar(' '); else sp = true; printf(fmt, *begin); }
putchar('\n');
}
template<class T> struct DiffSet {
multiset<T> num, diff;
DiffSet() { }
// data is not a ref;
DiffSet(vector<T> data) {
sort(data.begin(), data.end());
num = multiset<T>(data.begin(), data.end());
if (data.size() >= 2u) {
for (int i=data.size()-2u; i>=0; i--) data[i+1] -= data[i];
diff = multiset<T>(data.begin()+1, data.end());
}
}
// insert v if doesn't have;
bool insert_unique(const T &v) {
auto right = num.lower_bound(v);
if (right != num.end() && *right == v) return false;
if (right != num.begin()) {
auto left = prev(right);
if (right != num.end()) { diff.erase(diff.find(*right - *left)); }
diff.insert(v - *left);
}
if (right != num.end()) { diff.insert(*right - v); }
num.insert(v);
return true;
}
// insert v anyway;
bool insert_multi(const T &v) {
auto right = num.lower_bound(v);
if (right != num.begin()) {
auto left = prev(right);
if (right != num.end()) { diff.erase(diff.find(*right - *left)); }
diff.insert(v - *left);
}
if (right != num.end()) { diff.insert(*right - v); }
num.insert(v);
return true;
}
// erase single v if it has;
bool erase_one(const T &v) {
auto it = num.find(v);
if (it == num.end()) return false;
auto right = next(it);
if (right != num.end()) { diff.erase(diff.find(*right - v)); }
if (it != num.begin()) {
auto left = prev(it);
diff.erase(diff.find(v - *left));
if (right != num.end()) { diff.insert(*right - *left); }
}
num.erase(it);
return true;
}
bool empty() const {
return num.empty();
}
bool diff_empty() const {
return diff.empty();
}
bool contains(const T &v) const {
return num.find(v) != num.end();
}
bool diff_contains(const T &v) const {
return diff.find(v) != diff.end();
}
T max_diff() const {
assert(diff.size() >= 1u);
return *diff.rbegin();
}
T min_diff() const {
assert(diff.size() >= 1u);
return *diff.begin();
}
};
int N, Q;
int P[100011];
void MAIN() {
scanf("%d%d", &N, &Q);
REP (i, N) scanf("%d", P+i);
sort(P, P+N);
DiffSet<int> ds(VI(P, P+N));
auto print = [&]() {
int ans = 0;
if (!ds.diff_empty()) {
ans = *ds.num.rbegin() - *ds.num.begin() - ds.max_diff();
}
printf("%d\n", ans);
};
print();
REP ($, Q) {
int t, x;
scanf("%d%d", &t, &x);
if (t == 0) {
ds.erase_one(x);
} else {
ds.insert_multi(x);
}
print();
}
}
int main() {
int TC = 1;
// scanf("%d", &TC);
REP (tc, TC) MAIN();
return 0;
}
E. Expected Damage
方法 1.1
考虑计算一个怪会在多少种情况下对伤害产生贡献。
不妨将
下面使用 “将怪排成一排” 来思考和描述,而非 “依次出现”。
在某方案中,一个怪能产生贡献,当且仅当它前面有至少
考虑
如何计算
先将
考虑将当前的怪 “插入” 大怪的间隙中,一共有
然后将
注意这其实就是 “将
将上面的所有东西乘起来,得到:
考虑第
设满足
那么对于一个大怪
对于一个小怪
于是答案为:
其中,
方法 1.2
上面的式子可以继续化简。
先化简第一部分:
再化简第二部分:
于是答案为:
这样计算省去了组合数的计算,使代码更加简洁。
方法 2
这是一个直观理解方法 1.2 得出的式子的方法。
考虑计算一个大怪产生伤害的概率。
将所有大怪排成一排,显然这个大怪在这
所以一个大怪产生伤害的概率为
考虑计算一个小怪产生伤害的概率。
将所有大怪排成一排,考虑将这个小怪 “插入” 到大怪的间隙中。
共有
所以一个小怪产生伤害的概率为
于是答案为
My Code
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 2e5 + 5;
const int MAXM = 2e5 + 5;
const int MAXF = MAXN * 2;
const int mod = 998244353;
inline ll pw(ll a,ll b)
{
ll res = 1;
while(b)
{
if(b&1) res=res*a%mod;
a=a*a%mod; b>>=1;
}
return res;
}
ll fac[MAXF], inv[MAXF];
inline ll c(int n,int m){ return n<0||m<0||n<m? 0: fac[n] * inv[m] %mod * inv[n-m] %mod;}
int d[MAXN];
ll sum[MAXN];
inline ll calc(ll x,ll y,ll a)
{
if(x<0 || y<0 || x<a) return 0;
return fac[x] * (x-a+1) %mod * fac[y] %mod * c(y+x+1,x+1) %mod;
}
int main(void)
{
fac[0] = 1;
for(int i=1; i<MAXF; ++i) fac[i] = fac[i-1] * i %mod;
inv[MAXF-1] = pw(fac[MAXF-1], mod-2);
for(int i=MAXF-2; i>=0; --i) inv[i] = inv[i+1] * (i+1) %mod;
int n,m;
scanf("%d%d",&n,&m);
for(int i=1; i<=n; ++i) scanf("%d",&d[i]);
sort(d+1,d+n+1);
for(int i=1; i<=n; ++i)
sum[i] = (sum[i-1] + d[i]) %mod;
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
int pos = lower_bound(d+1,d+n+1,b) - d;
int x = n-pos+1, y = pos-1;
ll less = sum[pos-1] * calc(x,y-1,a) %mod;
ll grea = (sum[n] - sum[pos-1]) * calc(x-1,y,a) %mod;
printf("%lld\n",(less + grea + mod) %mod * inv[n] %mod);
}
return 0;
}
Code
neal
使用了最简便的式子。
#include <algorithm>
#include <array>
#include <cassert>
#include <iostream>
#include <vector>
using namespace std;
template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; }
template<typename T, size_t size> ostream& operator<<(ostream &os, const array<T, size> &arr) { os << '{'; string sep; for (const auto &x : arr) os << sep << x, sep = ", "; return os << '}'; }
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
#ifdef NEAL_DEBUG
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif
template<const int &MOD>
struct _m_int {
int val;
_m_int(int64_t v = 0) {
if (v < 0) v = v % MOD + MOD;
if (v >= MOD) v %= MOD;
val = int(v);
}
_m_int(uint64_t v) {
if (v >= MOD) v %= MOD;
val = int(v);
}
_m_int(int v) : _m_int(int64_t(v)) {}
_m_int(unsigned v) : _m_int(uint64_t(v)) {}
static int inv_mod(int a, int m = MOD) {
// https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Example
int g = m, r = a, x = 0, y = 1;
while (r != 0) {
int q = g / r;
g %= r; swap(g, r);
x -= q * y; swap(x, y);
}
return x < 0 ? x + m : x;
}
explicit operator int() const { return val; }
explicit operator unsigned() const { return val; }
explicit operator int64_t() const { return val; }
explicit operator uint64_t() const { return val; }
explicit operator double() const { return val; }
explicit operator long double() const { return val; }
_m_int& operator+=(const _m_int &other) {
val -= MOD - other.val;
if (val < 0) val += MOD;
return *this;
}
_m_int& operator-=(const _m_int &other) {
val -= other.val;
if (val < 0) val += MOD;
return *this;
}
static unsigned fast_mod(uint64_t x, unsigned m = MOD) {
#if !defined(_WIN32) || defined(_WIN64)
return unsigned(x % m);
#endif
// Optimized mod for Codeforces 32-bit machines.
// x must be less than 2^32 * m for this to work, so that x / m fits in an unsigned 32-bit int.
unsigned x_high = unsigned(x >> 32), x_low = unsigned(x);
unsigned quot, rem;
asm("divl %4\n"
: "=a" (quot), "=d" (rem)
: "d" (x_high), "a" (x_low), "r" (m));
return rem;
}
_m_int& operator*=(const _m_int &other) {
val = fast_mod(uint64_t(val) * other.val);
return *this;
}
_m_int& operator/=(const _m_int &other) {
return *this *= other.inv();
}
friend _m_int operator+(const _m_int &a, const _m_int &b) { return _m_int(a) += b; }
friend _m_int operator-(const _m_int &a, const _m_int &b) { return _m_int(a) -= b; }
friend _m_int operator*(const _m_int &a, const _m_int &b) { return _m_int(a) *= b; }
friend _m_int operator/(const _m_int &a, const _m_int &b) { return _m_int(a) /= b; }
_m_int& operator++() {
val = val == MOD - 1 ? 0 : val + 1;
return *this;
}
_m_int& operator--() {
val = val == 0 ? MOD - 1 : val - 1;
return *this;
}
_m_int operator++(int) { _m_int before = *this; ++*this; return before; }
_m_int operator--(int) { _m_int before = *this; --*this; return before; }
_m_int operator-() const {
return val == 0 ? 0 : MOD - val;
}
friend bool operator==(const _m_int &a, const _m_int &b) { return a.val == b.val; }
friend bool operator!=(const _m_int &a, const _m_int &b) { return a.val != b.val; }
friend bool operator<(const _m_int &a, const _m_int &b) { return a.val < b.val; }
friend bool operator>(const _m_int &a, const _m_int &b) { return a.val > b.val; }
friend bool operator<=(const _m_int &a, const _m_int &b) { return a.val <= b.val; }
friend bool operator>=(const _m_int &a, const _m_int &b) { return a.val >= b.val; }
_m_int inv() const {
return inv_mod(val);
}
_m_int pow(int64_t p) const {
if (p < 0)
return inv().pow(-p);
_m_int a = *this, result = 1;
while (p > 0) {
if (p & 1)
result *= a;
p >>= 1;
if (p > 0)
a *= a;
}
return result;
}
friend ostream& operator<<(ostream &os, const _m_int &m) {
return os << m.val;
}
};
extern const int MOD = 998244353;
using mod_int = _m_int<MOD>;
int main() {
ios::sync_with_stdio(false);
#ifndef NEAL_DEBUG
cin.tie(nullptr);
#endif
int N, M;
cin >> N >> M;
vector<int> D(N);
for (auto &d : D)
cin >> d;
sort(D.begin(), D.end());
vector<mod_int> D_prefix(N + 1, 0);
for (int i = 0; i < N; i++)
D_prefix[i + 1] = D_prefix[i] + D[i];
for (int q = 0; q < M; q++) {
int a, b;
cin >> a >> b;
int index = int(lower_bound(D.begin(), D.end(), b) - D.begin());
int big = N - index;
mod_int big_sum = D_prefix[N] - D_prefix[index];
mod_int small_sum = D_prefix[index];
if (a > big || a == N) {
cout << 0 << '\n';
continue;
}
mod_int big_answer = big_sum * (big - a) / big;
mod_int small_answer = small_sum * (big + 1 - a) / (big + 1);
cout << big_answer + small_answer << '\n';
}
}
tourist
/**
* author: tourist
* created: 14.09.2020 20:54:03
**/
#include <bits/stdc++.h>
using namespace std;
template <typename T>
T inverse(T a, T m) {
T u = 0, v = 1;
while (a != 0) {
T t = m / a;
m -= t * a; swap(a, m);
u -= t * v; swap(u, v);
}
assert(m == 1);
return u;
}
template <typename T>
class Modular {
public:
using Type = typename decay<decltype(T::value)>::type;
constexpr Modular() : value() {}
template <typename U>
Modular(const U& x) {
value = normalize(x);
}
template <typename U>
static Type normalize(const U& x) {
Type v;
if (-mod() <= x && x < mod()) v = static_cast<Type>(x);
else v = static_cast<Type>(x % mod());
if (v < 0) v += mod();
return v;
}
const Type& operator()() const { return value; }
template <typename U>
explicit operator U() const { return static_cast<U>(value); }
constexpr static Type mod() { return T::value; }
Modular& operator+=(const Modular& other) { if ((value += other.value) >= mod()) value -= mod(); return *this; }
Modular& operator-=(const Modular& other) { if ((value -= other.value) < 0) value += mod(); return *this; }
template <typename U> Modular& operator+=(const U& other) { return *this += Modular(other); }
template <typename U> Modular& operator-=(const U& other) { return *this -= Modular(other); }
Modular& operator++() { return *this += 1; }
Modular& operator--() { return *this -= 1; }
Modular operator++(int) { Modular result(*this); *this += 1; return result; }
Modular operator--(int) { Modular result(*this); *this -= 1; return result; }
Modular operator-() const { return Modular(-value); }
template <typename U = T>
typename enable_if<is_same<typename Modular<U>::Type, int>::value, Modular>::type& operator*=(const Modular& rhs) {
#ifdef _WIN32
uint64_t x = static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value);
uint32_t xh = static_cast<uint32_t>(x >> 32), xl = static_cast<uint32_t>(x), d, m;
asm(
"divl %4; \n\t"
: "=a" (d), "=d" (m)
: "d" (xh), "a" (xl), "r" (mod())
);
value = m;
#else
value = normalize(static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value));
#endif
return *this;
}
template <typename U = T>
typename enable_if<is_same<typename Modular<U>::Type, int64_t>::value, Modular>::type& operator*=(const Modular& rhs) {
int64_t q = static_cast<int64_t>(static_cast<long double>(value) * rhs.value / mod());
value = normalize(value * rhs.value - q * mod());
return *this;
}
template <typename U = T>
typename enable_if<!is_integral<typename Modular<U>::Type>::value, Modular>::type& operator*=(const Modular& rhs) {
value = normalize(value * rhs.value);
return *this;
}
Modular& operator/=(const Modular& other) { return *this *= Modular(inverse(other.value, mod())); }
template <typename U>
friend const Modular<U>& abs(const Modular<U>& v) { return v; }
template <typename U>
friend bool operator==(const Modular<U>& lhs, const Modular<U>& rhs);
template <typename U>
friend bool operator<(const Modular<U>& lhs, const Modular<U>& rhs);
template <typename U>
friend std::istream& operator>>(std::istream& stream, Modular<U>& number);
private:
Type value;
};
template <typename T> bool operator==(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value == rhs.value; }
template <typename T, typename U> bool operator==(const Modular<T>& lhs, U rhs) { return lhs == Modular<T>(rhs); }
template <typename T, typename U> bool operator==(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) == rhs; }
template <typename T> bool operator!=(const Modular<T>& lhs, const Modular<T>& rhs) { return !(lhs == rhs); }
template <typename T, typename U> bool operator!=(const Modular<T>& lhs, U rhs) { return !(lhs == rhs); }
template <typename T, typename U> bool operator!=(U lhs, const Modular<T>& rhs) { return !(lhs == rhs); }
template <typename T> bool operator<(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value < rhs.value; }
template <typename T> Modular<T> operator+(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }
template <typename T, typename U> Modular<T> operator+(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) += rhs; }
template <typename T, typename U> Modular<T> operator+(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }
template <typename T> Modular<T> operator-(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }
template <typename T, typename U> Modular<T> operator-(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) -= rhs; }
template <typename T, typename U> Modular<T> operator-(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }
template <typename T> Modular<T> operator*(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }
template <typename T, typename U> Modular<T> operator*(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) *= rhs; }
template <typename T, typename U> Modular<T> operator*(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }
template <typename T> Modular<T> operator/(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; }
template <typename T, typename U> Modular<T> operator/(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) /= rhs; }
template <typename T, typename U> Modular<T> operator/(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; }
template<typename T, typename U>
Modular<T> power(const Modular<T>& a, const U& b) {
assert(b >= 0);
Modular<T> x = a, res = 1;
U p = b;
while (p > 0) {
if (p & 1) res *= x;
x *= x;
p >>= 1;
}
return res;
}
template <typename T>
bool IsZero(const Modular<T>& number) {
return number() == 0;
}
template <typename T>
string to_string(const Modular<T>& number) {
return to_string(number());
}
template <typename T>
std::ostream& operator<<(std::ostream& stream, const Modular<T>& number) {
return stream << number();
}
template <typename T>
std::istream& operator>>(std::istream& stream, Modular<T>& number) {
typename common_type<typename Modular<T>::Type, int64_t>::type x;
stream >> x;
number.value = Modular<T>::normalize(x);
return stream;
}
/*
using ModType = int;
struct VarMod { static ModType value; };
ModType VarMod::value;
ModType& md = VarMod::value;
using Mint = Modular<VarMod>;
*/
constexpr int md = 998244353;
using Mint = Modular<std::integral_constant<decay<decltype(md)>::type, md>>;
vector<Mint> fact(1, 1);
vector<Mint> inv_fact(1, 1);
Mint C(int n, int k) {
if (k < 0 || k > n) {
return 0;
}
while ((int) fact.size() < n + 1) {
fact.push_back(fact.back() * (int) fact.size());
inv_fact.push_back(1 / fact.back());
}
return fact[n] * inv_fact[k] * inv_fact[n - k];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n >> m;
vector<int> d(n);
for (int i = 0; i < n; i++) {
cin >> d[i];
}
sort(d.begin(), d.end());
vector<Mint> pref(n + 1);
for (int i = 0; i < n; i++) {
pref[i + 1] = pref[i] + d[i];
}
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
int pos = (int) (lower_bound(d.begin(), d.end(), b) - d.begin());
int big = n - pos;
if (big < a) {
cout << 0 << '\n';
continue;
}
// big >= a
// each big monster deals its damage with probability (big - a) / big
// by linearity of expectation, the expected damage received from big monsters is...
Mint damage_from_big = (pref[n] - pref[pos]) * (big - a) / big;
// small monster deals its damage if it comes after the a-th big monster
// we have some big monsters
// O big O big O ...... O big O
// we have big+1 positions
// and there are a "bad" positions
// and (big+1-a) "good" positions ("good" means that the small monster deals its damage)
// the probability is thus (big + 1 - a) / (big + 1)
Mint damage_from_small = pref[pos] * (big + 1 - a) / (big + 1);
cout << damage_from_big + damage_from_small << '\n';
}
return 0;
}
G. Three Occurrences
方法 1 线段树
考虑从前往后枚举区间的右端点
考虑对于一个数
举个例子:
. . X . x . . X . . X . . . X . . .
上面表示从 X 表示 . 表示其他数。
如果用
. . X . x . . X . . X . . . X . . .
0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 1 1 1
注意到,可以成为左端点的位置只有:
- 倒数第三次出现
x 的位置前。 - 最后一次出现
x 的位置后。
换句话说,如果用
如果一个位置可能成为左端点,我们称这个位置对于
注意到,一个位置可以成为左端点,当且仅当对于所有
考虑如何维护。注意到
. . X . x . . X . . X . . . X . . .
1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 0 0 0
我们将所有
举个例子:
3 2 3 3 1 3 2 1 2 2 1
for 1: 0 0 0 0 0 1 1 1 1 1 1
for 2: 1 1 0 0 0 0 0 1 1 1 1
for 3: 1 0 0 1 1 1 1 1 1 1 1
sum: 2 1 0 1 1 2 2 3 3 3 3
注意到只有
在进行 “区间交” 的统计时,将有用的区间的贡献设为
我们需要一种数据结构,支持区间加,以及查询区间的
注意到一个点的贡献和不可能小于
My Code
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 5e5 + 5;
const int inf = 0x3f3f3f3f;
struct Segment_Tree
{
pii mn[MAXN<<2];
int tag[MAXN<<2];
#define ls(u) ((u)<<1)
#define rs(u) ((u)<<1|1)
#define lson(u) ls(u),l,mid
#define rson(u) rs(u),mid+1,r
inline void clear(void){ memset(mn,0,sizeof(mn)); memset(tag,0,sizeof(tag));}
inline void upd(pii &p,const pii &q)
{
if(p.first == q.first) p.second += q.second;
else p = min(p,q);
}
inline void push_up(int u)
{
if(mn[ls(u)].first == mn[rs(u)].first)
mn[u] = mn[ls(u)], mn[u].second += mn[rs(u)].second;
else mn[u] = min(mn[ls(u)], mn[rs(u)]);
}
inline void push_down(int u)
{
if(tag[u])
{
mn[ls(u)].first += tag[u]; tag[ls(u)] += tag[u];
mn[rs(u)].first += tag[u]; tag[rs(u)] += tag[u];
tag[u] = 0;
}
}
void build(int u,int l,int r,int k)
{
mn[u] = make_pair(k,r-l+1); tag[u] = 0;
if(l==r) return;
int mid = (l+r)>>1;
build(lson(u),k); build(rson(u),k);
}
void update(int u,int l,int r,int ql,int qr,int k)
{
if(ql<=l && r<=qr){ mn[u].first += k; tag[u] += k; return;}
push_down(u);
int mid = (l+r)>>1;
if(ql<=mid) update(lson(u),ql,qr,k);
if(mid<qr) update(rson(u),ql,qr,k);
push_up(u);
}
pii query(int u,int l,int r,int ql,int qr)
{
if(ql<=l && r<=qr) return mn[u];
push_down(u);
int mid = (l+r)>>1; pii res = make_pair(inf,0);
if(ql<=mid) upd(res, query(lson(u),ql,qr));
if(mid<qr) upd(res, query(rson(u),ql,qr));
return res;
}
};
int a[MAXN];
int main(void)
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
static Segment_Tree tree;
static int lst[MAXN][4];
tree.build(1,1,n,0);
ll ans = 0;
for(int i=1; i<=n; ++i)
{
int *occ = lst[a[i]];
if(occ[2]) tree.update(1,1,n, occ[3]+1, occ[2], 1);
for(int j=3; j>0; --j) occ[j] = occ[j-1];
occ[0] = i;
tree.update(1,1,n, occ[1]+1,i, 1);
if(occ[2]) tree.update(1,1,n, occ[3]+1, occ[2], -1);
pii res = tree.query(1,1,n, 1,i);
if(!res.first) ans += res.second;
}
printf("%lld",ans);
return 0;
}
方法 2 Hash
考虑如果限制条件不是 “出现恰好
不妨对每个前缀
发现,一个区间
于是对
考虑 “出现过的数出现次数恰好为
于是可以使用 two pointers,向右移动 map 维护区间
My Code
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 5e5 + 5;
struct Hash
{
int base,mod, pw[MAXN], cur_val;
Hash(int base,int mod = 1e9 + 7): base(base), mod(mod), cur_val(0)
{
pw[0] = 1;
for(int i=1; i<MAXN; ++i) pw[i] = (ll)pw[i-1] * base %mod;
}
inline int calc_dig(int pos,int x){ return (ll)x * pw[pos] %mod;}
inline void add_dig(int pos,int x){ cur_val = (cur_val + (ll)x * pw[pos]) %mod;}
inline void sub_dig(int pos,int x){ cur_val = (cur_val - (ll)x * pw[pos] %mod + mod) %mod;}
inline int get_hash(void){ return cur_val;}
};
struct Double_Hash
{
Hash h1,h2;
Double_Hash(int base1,int base2,int mod1=1e9+7,int mod2=1e9+7): h1(base1,mod1), h2(base2,mod2) {}
inline pii get_dig(int pos,int x){ return make_pair(h1.calc_dig(pos,x), h2.calc_dig(pos,x));}
inline void add_dig(int pos,int x){ h1.add_dig(pos,x); h2.add_dig(pos,x);}
inline void sub_dig(int pos,int x){ h1.sub_dig(pos,x); h2.sub_dig(pos,x);}
inline pii get_hash(void){ return make_pair(h1.get_hash(), h2.get_hash());}
};
int a[MAXN];
int main(void)
{
srand(time(0));
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
ll ans = 0;
static int freq[MAXN], val[MAXN];
static Double_Hash h(114514+rand(), 1919810+rand());
static pii hs[MAXN];
map<pii,int> occ;
for(int i=1,j=1; i<=n; ++i)
{
int x = a[i];
h.sub_dig(x, val[x]);
++freq[x];
val[x] = (val[x] + 1)%3;
h.add_dig(x, val[x]);
hs[i] = h.get_hash();
while(freq[x] > 3)
{
--occ[hs[j]];
--freq[a[j]];
++j;
}
ans += occ[hs[i]]++ + (hs[i] == hs[j-1]);
}
printf("%lld",ans);
return 0;
}
方法 3 随机化
考虑对于每个数赋值。考虑对于每个数
再对每个位置
举个例子,设数 X 表示,其它位置用 . 表示。
a: . . X . x . . X . . X . . . X . . X . .
val: . . v . v . .-2v. . v . . . v . .-2v. .
注意到,如果
发现
- 赋的
val 可能发生 “冲突” 的情况,类似哈希冲突。 - 只保证出现次数为
3 的倍数,不保证其\leq 3 。
对于第一点,只需要给在确定 rand() 的最大值是不低于 rand() 的话,可能会导致随机数的范围十分小。
解决这个问题,可以使用诸如 rand()<<15|rand()(假设 rand() 的最大值为 ((ll)rand()<<30) | ((ll)rand()<<15) | (ll)rand(),可以使随机数的范围扩大很多。
另外,一定要记得 srand(),但是使用 time(0) 并不能保证代码不被卡掉,推荐使用一个变量的地址,如 srand((unsigned long long)new char);。
对于第二点,可以参考上面的 “方法 2 Hash”。使用 two pointers,向右移动 map 维护
这种方法的优点是,代码非常简短。
My Code
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
const int MAXN = 5e5 + 5;
inline ll rnd(void){ return ((ll)rand()<<30) | ((ll)rand()<<15) | (ll)rand();}
int a[MAXN];
ll val[MAXN], sum[MAXN];
int main(void)
{
char rrrand;
srand((ull)&rrrand);
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
for(int i=1; i<=n; ++i) val[i] = rnd();
static int freq[MAXN];
for(int i=1; i<=n; ++i)
{
++freq[a[i]];
if(freq[a[i]]%3) sum[i] = sum[i-1] + val[a[i]];
else sum[i] = sum[i-1] - 2 * val[a[i]];
}
ll ans = 0;
map<ll,int> t;
memset(freq,0,sizeof(freq));
for(int i=1,j=1; i<=n; ++i)
{
++freq[a[i]];
while(freq[a[i]] > 3)
{
--freq[a[j]];
--t[sum[j]];
++j;
}
ans += t[sum[i]] + (sum[i] == sum[j-1]);
++t[sum[i]];
}
printf("%lld",ans);
return 0;
}
方法 4 XOR Hashing
考虑如果不限制出现次数恰好为
设在前缀
考虑计算对于每个前缀
那么一个子段
考虑限制出现次数恰好为
于是就可以使用 two pointers 来维护左边界,使用 map 来维护
注意这个
和 “方法 3 随机化” 比较相似,但对异或的使用避免了对溢出等问题的考虑。
My Code
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 5e5 + 5;
inline ll rnd(void){ return ((ll)rand()<<45) | ((ll)rand()<<30) | (rand()<<15) | rand();}
int a[MAXN];
ll val[MAXN], h[MAXN];
int main(void)
{
srand((unsigned long long)new char);
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
for(int i=1; i<=n; ++i) val[i] = rnd();
ll ans = 0;
map<ll,int> t;
t[0] = 1;
for(int i=1,j=1; i<=n; ++i)
{
static int freq[MAXN];
++freq[a[i]];
while(freq[a[i]] > 3) --t[h[j-1]], --freq[a[j]], ++j;
static int coef[MAXN];
h[i] = h[i-1] ^ (val[a[i]] * coef[a[i]]);
coef[a[i]] = (coef[a[i]] + 1) % 3;
h[i] ^= (val[a[i]] * coef[a[i]]);
ans += t[h[i]]++;
}
printf("%lld",ans);
return 0;
}
Code
neal
使用了方法 3。
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <iostream>
#include <queue>
#include <random>
#include <unordered_map>
#include <vector>
using namespace std;
template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; }
template<typename T, size_t size> ostream& operator<<(ostream &os, const array<T, size> &arr) { os << '{'; string sep; for (const auto &x : arr) os << sep << x, sep = ", "; return os << '}'; }
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
#ifdef NEAL_DEBUG
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif
auto random_address = [] { char *p = new char; delete p; return uint64_t(p); };
const uint64_t SEED = chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1);
mt19937_64 rng(SEED);
int main() {
ios::sync_with_stdio(false);
#ifndef NEAL_DEBUG
cin.tie(nullptr);
#endif
using hash_t = uint64_t;
int N;
cin >> N;
vector<int> A(N);
for (auto &a : A)
cin >> a;
vector<hash_t> hash_values(N + 1);
for (int i = 0; i <= N; i++)
hash_values[i] = rng();
hash_t hash = 0;
unordered_map<hash_t, int> hash_freq;
hash_freq[hash]++;
vector<int> freq(N + 1, 0);
vector<queue<int>> indices(N + 1);
vector<hash_t> hashes(N + 1, 0);
int64_t answer = 0;
int start = 0;
for (int i = 0; i < N; i++) {
int a = A[i];
if (indices[a].size() >= 3) {
int remove = indices[a].front(); indices[a].pop();
dbg(i, remove);
while (start < remove) {
hash_freq[hashes[start]]--;
start++;
}
}
hash -= freq[a] * hash_values[a];
freq[a] = (freq[a] + 1) % 3;
hash += freq[a] * hash_values[a];
hashes[i + 1] = hash;
answer += hash_freq[hash]++;
indices[a].push(i + 1);
dbg(i, answer);
}
cout << answer << '\n';
}
tourist
使用了方法 1,即线段树,将合法点的贡献设为
/**
* author: tourist
* created: 14.09.2020 21:11:08
**/
#include <bits/stdc++.h>
using namespace std;
class segtree {
public:
struct node {
// don't forget to set default value (used for leaves)
// not necessarily neutral element!
int mx = 0;
int add = 0;
int cnt = 1;
void apply(int l, int r, int v) {
add += v;
mx += v;
}
};
node unite(const node &a, const node &b) const {
node res;
res.mx = max(a.mx, b.mx);
res.cnt = (res.mx == a.mx ? a.cnt : 0) + (res.mx == b.mx ? b.cnt : 0);
return res;
}
inline void push(int x, int l, int r) {
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
if (tree[x].add != 0) {
tree[x + 1].apply(l, y, tree[x].add);
tree[z].apply(y + 1, r, tree[x].add);
tree[x].add = 0;
}
}
inline void pull(int x, int z) {
tree[x] = unite(tree[x + 1], tree[z]);
}
int n;
vector<node> tree;
void build(int x, int l, int r) {
if (l == r) {
return;
}
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
build(x + 1, l, y);
build(z, y + 1, r);
pull(x, z);
}
template <typename M>
void build(int x, int l, int r, const vector<M> &v) {
if (l == r) {
tree[x].apply(l, r, v[l]);
return;
}
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
build(x + 1, l, y, v);
build(z, y + 1, r, v);
pull(x, z);
}
node get(int x, int l, int r, int ll, int rr) {
if (ll <= l && r <= rr) {
return tree[x];
}
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
push(x, l, r);
node res{};
if (rr <= y) {
res = get(x + 1, l, y, ll, rr);
} else {
if (ll > y) {
res = get(z, y + 1, r, ll, rr);
} else {
res = unite(get(x + 1, l, y, ll, rr), get(z, y + 1, r, ll, rr));
}
}
pull(x, z);
return res;
}
template <typename... M>
void modify(int x, int l, int r, int ll, int rr, const M&... v) {
if (ll <= l && r <= rr) {
tree[x].apply(l, r, v...);
return;
}
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
push(x, l, r);
if (ll <= y) {
modify(x + 1, l, y, ll, rr, v...);
}
if (rr > y) {
modify(z, y + 1, r, ll, rr, v...);
}
pull(x, z);
}
int find_first_knowingly(int x, int l, int r, const function<bool(const node&)> &f) {
if (l == r) {
return l;
}
push(x, l, r);
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
int res;
if (f(tree[x + 1])) {
res = find_first_knowingly(x + 1, l, y, f);
} else {
res = find_first_knowingly(z, y + 1, r, f);
}
pull(x, z);
return res;
}
int find_first(int x, int l, int r, int ll, int rr, const function<bool(const node&)> &f) {
if (ll <= l && r <= rr) {
if (!f(tree[x])) {
return -1;
}
return find_first_knowingly(x, l, r, f);
}
push(x, l, r);
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
int res = -1;
if (ll <= y) {
res = find_first(x + 1, l, y, ll, rr, f);
}
if (rr > y && res == -1) {
res = find_first(z, y + 1, r, ll, rr, f);
}
pull(x, z);
return res;
}
int find_last_knowingly(int x, int l, int r, const function<bool(const node&)> &f) {
if (l == r) {
return l;
}
push(x, l, r);
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
int res;
if (f(tree[z])) {
res = find_last_knowingly(z, y + 1, r, f);
} else {
res = find_last_knowingly(x + 1, l, y, f);
}
pull(x, z);
return res;
}
int find_last(int x, int l, int r, int ll, int rr, const function<bool(const node&)> &f) {
if (ll <= l && r <= rr) {
if (!f(tree[x])) {
return -1;
}
return find_last_knowingly(x, l, r, f);
}
push(x, l, r);
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
int res = -1;
if (rr > y) {
res = find_last(z, y + 1, r, ll, rr, f);
}
if (ll <= y && res == -1) {
res = find_last(x + 1, l, y, ll, rr, f);
}
pull(x, z);
return res;
}
segtree(int _n) : n(_n) {
assert(n > 0);
tree.resize(2 * n - 1);
build(0, 0, n - 1);
}
template <typename M>
segtree(const vector<M> &v) {
n = v.size();
assert(n > 0);
tree.resize(2 * n - 1);
build(0, 0, n - 1, v);
}
node get(int ll, int rr) {
assert(0 <= ll && ll <= rr && rr <= n - 1);
return get(0, 0, n - 1, ll, rr);
}
node get(int p) {
assert(0 <= p && p <= n - 1);
return get(0, 0, n - 1, p, p);
}
template <typename... M>
void modify(int ll, int rr, const M&... v) {
assert(0 <= ll && ll <= rr && rr <= n - 1);
modify(0, 0, n - 1, ll, rr, v...);
}
// find_first and find_last call all FALSE elements
// to the left (right) of the sought position exactly once
int find_first(int ll, int rr, const function<bool(const node&)> &f) {
assert(0 <= ll && ll <= rr && rr <= n - 1);
return find_first(0, 0, n - 1, ll, rr, f);
}
int find_last(int ll, int rr, const function<bool(const node&)> &f) {
assert(0 <= ll && ll <= rr && rr <= n - 1);
return find_last(0, 0, n - 1, ll, rr, f);
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
--a[i];
}
// if we have array x x x x 1 x x x x 1 x x x 1 x x x 1 x x x 1 x x x
// [ ]
// [ ]
// [ ]
// [ ]
// [ ]
// [ ]
// [ ]
// [ ]
segtree st(n);
vector<vector<int>> pos(n);
for (int i = 0; i < n; i++) {
pos[i].push_back(n);
st.modify(0, n - 1, +1);
}
long long ans = 0;
for (int l = n - 1; l >= 0; l--) {
int v = a[l];
{
if (pos[v].size() >= 4) {
int third = pos[v][pos[v].size() - 3];
int fourth = pos[v][pos[v].size() - 4];
st.modify(third, fourth - 1, -1);
}
st.modify(0, pos[v].back() - 1, -1);
}
pos[v].push_back(l);
{
if (pos[v].size() >= 4) {
int third = pos[v][pos[v].size() - 3];
int fourth = pos[v][pos[v].size() - 4];
st.modify(third, fourth - 1, +1);
}
if (pos[v].back() > 0) {
st.modify(0, pos[v].back() - 1, +1);
}
}
auto nd = st.get(l, n - 1);
if (nd.mx == n) {
ans += nd.cnt;
}
}
cout << ans << '\n';
return 0;
}
WZYYN
线段树写得十分简洁。
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned ll
#define uint unsigned
#define pii pair<int,int>
#define pll pair<ll,ll>
#define IT iterator
#define PB push_back
#define fi first
#define se second
#define For(i,j,k) for (int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for (int i=(int)(j);i>=(int)(k);i--)
#define CLR(a,v) memset(a,v,sizeof(a));
#define CPY(a,b) memcpy(a,b,sizeof(a));
#define debug puts("wzpakking")
#define y1 ysghysgsygsh
using namespace std;
const int N=500005;
int n,a[N];
vector<int> op[N];
int pos[N];
pii mx[N*4];
int tg[N*4];
void build(int k,int l,int r){
mx[k]=pii(0,r-l+1);
if (l==r) return;
int mid=(l+r)/2;
build(k*2,l,mid);
build(k*2+1,mid+1,r);
}
void change(int k,int l,int r,int x,int y,int v){
if (x<=l&&r<=y){
tg[k]+=v;
mx[k].fi+=v;
return;
}
int mid=(l+r)/2;
if (x<=mid) change(k*2,l,mid,x,y,v);
if (y>mid) change(k*2+1,mid+1,r,x,y,v);
mx[k]=pii(max(mx[k*2].fi,mx[k*2+1].fi),0);
if (mx[k].fi==mx[k*2].fi) mx[k].se+=mx[k*2].se;
if (mx[k].fi==mx[k*2+1].fi) mx[k].se+=mx[k*2+1].se;
mx[k].fi+=tg[k];
}
void change(int x,int v){
change(1,0,n,op[x][pos[x]],op[x][pos[x]+1]-1,v);
if (pos[x]+3<op[x].size()-1)
change(1,0,n,op[x][pos[x]+3],op[x][pos[x]+4]-1,v);
}
int main(){
scanf("%d",&n);
For(i,1,n) scanf("%d",&a[i]);
For(i,1,n) op[i].PB(0);
For(i,1,n) op[a[i]].PB(i);
For(i,1,n) op[i].PB(n+1);
build(1,0,n);
For(i,1,n){
pos[i]=0;
change(i,1);
}
ll ans=0;
For(i,1,n){
change(1,0,n,i-1,i-1,-233333);
if (mx[1].fi==n)
ans+=mx[1].se;
//cout<<mx[1].fi<<' '<<mx[1].se<<' '<<i<<endl;
change(a[i],-1);
++pos[a[i]];
change(a[i],1);
}
cout<<ans<<endl;
}
noimi
使用了哈希。
#pragma region Macros
#pragma GCC optimize("O3")
#pragma GCC target("avx2,avx")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define rep2(i, a, b) for(ll i = a; i <= b; ++i)
#define rep(i, n) for(ll i = 0; i < n; ++i)
#define rep3(i, a, b) for(ll i = a; i >= b; --i)
#define pii pair<int, int>
#define pll pair<ll, ll>
#define pb push_back
#define eb emplace_back
#define vi vector<int>
#define vll vector<ll>
#define vpi vector<pii>
#define vpll vector<pll>
#define overload2(_1, _2, name, ...) name
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define VEC(type, name, size) \
vector<type> name(size); \
IN(name)
#define vv(type, name, h, ...) vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define VV(type, name, h, w) \
vector<vector<type>> name(h, vector<type>(w)); \
IN(name)
#define vvv(type, name, h, w, ...) vector<vector<vector<type>>> name(h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...) \
vector<vector<vector<vector<type>>>> name(a, vector<vector<vector<type>>>(b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
#define fi first
#define se second
#define all(c) begin(c), end(c)
#define lb(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define ub(c, x) distance((c).begin(), upper_bound(all(c), (x)))
using namespace std;
string YES[2] = {"NO", "YES"};
string Yes[2] = {"No", "Yes"};
string yes[2] = {"no", "yes"};
template <class T> using pq = priority_queue<T>;
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
#define si(c) (int)(c).size()
#define INT(...) \
int __VA_ARGS__; \
IN(__VA_ARGS__)
#define LL(...) \
ll __VA_ARGS__; \
IN(__VA_ARGS__)
#define STR(...) \
string __VA_ARGS__; \
IN(__VA_ARGS)
#define CHR(...) \
char __VA_ARGS__; \
IN(__VA_ARGS)
#define DBL(...) \
double __VA_ARGS__; \
IN(__VA_ARGS)
int scan() { return getchar(); }
void scan(int &a) { cin >> a; }
void scan(long long &a) { cin >> a; }
void scan(char &a) { cin >> a; }
void scan(double &a) { cin >> a; }
void scan(string &a) { cin >> a; }
template <class T, class S> void scan(pair<T, S> &p) { scan(p.first), scan(p.second); }
template <class T> void scan(vector<T> &);
template <class T> void scan(vector<T> &a) {
for(auto &i : a) scan(i);
}
template <class T> void scan(T &a) { cin >> a; }
void IN() {}
template <class Head, class... Tail> void IN(Head &head, Tail &... tail) {
scan(head);
IN(tail...);
}
template <class T, class S> inline bool chmax(T &a, S b) {
if(a < b) {
a = b;
return 1;
}
return 0;
}
template <class T, class S> inline bool chmin(T &a, S b) {
if(a > b) {
a = b;
return 1;
}
return 0;
}
vi iota(int n) {
vi a(n);
iota(all(a), 0);
return a;
}
#define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end())
vector<pll> factor(ll x) {
vector<pll> ans;
for(ll i = 2; i * i <= x; i++)
if(x % i == 0) {
ans.push_back({i, 1});
while((x /= i) % i == 0) ans.back().second++;
}
if(x != 1) ans.push_back({x, 1});
return ans;
}
template <class T> vector<T> divisor(T x) {
vector<T> ans;
for(T i = 1; i * i <= x; i++)
if(x % i == 0) {
ans.pb(i);
if(i * i != x) ans.pb(x / i);
}
return ans;
}
template <typename T> void zip(vector<T> &x) {
vector<T> y = x;
sort(all(y));
for(int i = 0; i < x.size(); ++i) { x[i] = lb(y, x[i]); }
}
int popcount(ll x) { return __builtin_popcountll(x); }
struct Setup_io {
Setup_io() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cout << fixed << setprecision(15);
}
} setup_io;
int in() {
int x;
cin >> x;
return x;
}
ll lin() {
unsigned long long x;
cin >> x;
return x;
}
template <typename T> struct edge {
int from, to;
T cost;
int id;
edge(int to, T cost) : from(-1), to(to), cost(cost) {}
edge(int from, int to, T cost) : from(from), to(to), cost(cost) {}
edge(int from, int to, T cost, int id) : from(from), to(to), cost(cost), id(id) {}
edge &operator=(const int &x) {
to = x;
return *this;
}
operator int() const { return to; }
};
template <typename T> using Edges = vector<edge<T>>;
using Tree = vector<vector<int>>;
using Graph = vector<vector<int>>;
template <class T> using Wgraph = vector<vector<edge<T>>>;
Graph getG(int n, int m = -1, bool directed = false, int margin = 1) {
Tree res(n);
if(m == -1) m = n - 1;
while(m--) {
int a, b;
cin >> a >> b;
a -= margin, b -= margin;
res[a].emplace_back(b);
if(!directed) res[b].emplace_back(a);
}
return move(res);
}
template <class T> Wgraph<T> getWg(int n, int m = -1, bool directed = false, int margin = 1) {
Wgraph<T> res(n);
if(m == -1) m = n - 1;
while(m--) {
int a, b;
T c;
cin >> a >> b >> c;
a -= margin, b -= margin;
res[a].emplace_back(b, c);
if(!directed) res[b].emplace_back(a, c);
}
return move(res);
}
#define i128 __int128_t
#define ull unsigned long long int
#define TEST \
INT(testcases); \
while(testcases--)
template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {
for(auto &e : v) cout << e << " ";
cout << endl;
return os;
}
template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &p) {
cout << "(" << p.fi << ", " << p.se << ")";
return os;
}
template <class S, class T> string to_string(pair<S, T> p) { return "(" + to_string(p.first) + "," + to_string(p.second) + ")"; }
template <class A> string to_string(A v) {
if(v.empty()) return "{}";
string ret = "{";
for(auto &x : v) ret += to_string(x) + ",";
ret.back() = '}';
return ret;
}
void dump() { cerr << endl; }
template <class Head, class... Tail> void dump(Head head, Tail... tail) {
cerr << to_string(head) << " ";
dump(tail...);
}
#define endl '\n'
#ifdef _LOCAL
#undef endl
#define debug(x) \
cout << #x << ": "; \
dump(x)
#else
#define debug(x)
#endif
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int rnd(int n) { return uniform_int_distribution<int>(0, n - 1)(rng); }
ll rndll(ll n) { return uniform_int_distribution<ll>(0, n - 1)(rng); }
template <typename T> static constexpr T inf = numeric_limits<T>::max() / 2;
#pragma endregion
static ull base, margin;
vector<ull> p{1};
static constexpr ull MOD = (1LL << 61) - 1;
vector<ull> h;
ull mul(ull a, ull b) {
i128 t = (i128)(a) * (i128)(b);
t = (t >> 61) + (t & MOD);
if(t >= MOD) return t - MOD;
return t;
}
ull add(ull a, ull b) { return (a + b) % MOD; }
ull sub(ull a, ull b) { return (a + MOD - b) % MOD; }
main() {
base = rnd(INT_MAX), margin = rnd(INT_MAX);
INT(n);
rep(i, n + 1) p.eb(mul(p.back(), base));
ll ans = 0;
map<ull, ll> mp;
ll hash = 0;
rep(i, n + 1) hash = add(hash, mul(p[i], margin));
mp[hash]++;
vll now(n + 1), mem(n + 1), left(n + 1);
int l = 0;
mem[0] = hash;
vi A(n);
rep(i, n) {
INT(a);
A[i] = a;
hash = sub(hash, mul(p[a], now[a] % 3 + margin));
now[a]++;
hash = add(hash, mul(p[a], now[a] % 3 + margin));
while(now[a] == left[a] + 6) {
mp[mem[l]]--;
left[A[l++]]++;
}
ans += mp[hash]++;
mem[i + 1] = hash;
}
cout << ans << endl;
}
Um_nik (方法 4)
注意到,一个合法区间的长度只可能是
对于一段长度为
-
- 其中出现的数的个数恰好为
len/3 。 - 其中每个数的出现次数不超过
3 。
注意其中的第三条,只要满足 ”不超过“ 即可。想一想,为什么。
于是可以用线段树来维护。
考虑枚举区间的左端点
对于一个
它就是一个合法的右端点。
考虑对每个位置
考虑处理出,对于每个位置
从大到小枚举
这么做的目的是,当
而且,因为保证了
于是,使用线段树维护
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <bitset>
using namespace std;
#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__);fflush(stderr);
#else
#define eprintf(...) 42
#endif
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;
template<typename T>
using pair2 = pair<T, T>;
using pii = pair<int, int>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
return (ull)rng() % B;
}
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
clock_t startTime;
double getCurrentTime() {
return (double)(clock() - startTime) / CLOCKS_PER_SEC;
}
const int INF = (int)1e8;
const int N = 1 << 19;
struct Node {
int l, r;
pii val;
int addAll;
Node() : l(), r(), val(), addAll(0) {}
Node(int _l, int _r) : l(_l), r(_r), val(mp(0, _r - _l)), addAll(0) {}
void add(int x) {
addAll += x;
val.first += x;
}
};
Node tree[2 * N + 5];
void build() {
for (int i = 0; i < N; i++)
tree[N + i] = Node(i, i + 1);
for (int i = N - 1; i > 0; i--)
tree[i] = Node(tree[2 * i].l, tree[2 * i + 1].r);
}
void push(int v) {
assert(v < N);
for (int u = 2 * v; u < 2 * v + 2; u++) {
tree[u].add(tree[v].addAll);
}
tree[v].addAll = 0;
}
pii merge(pii v, pii u) {
if (v.first != u.first) return min(v, u);
return mp(v.first, v.second + u.second);
}
void update(int v) {
assert(v < N);
tree[v].val = merge(tree[2 * v].val, tree[2 * v + 1].val);
}
void addSegm(int v, int l, int r, int x) {
if (l <= tree[v].l && tree[v].r <= r) {
tree[v].add(x);
return;
}
if (l >= tree[v].r || tree[v].l >= r) return;
push(v);
for (int u = 2 * v; u < 2 * v + 2; u++)
addSegm(u, l, r, x);
update(v);
}
pii getMin(int v, int l, int r) {
if (l <= tree[v].l && tree[v].r <= r) return tree[v].val;
if (l >= tree[v].r || tree[v].l >= r) return mp(INF, 0);
push(v);
return merge(getMin(2 * v, l, r), getMin(2 * v + 1, l, r));
}
const int M = 500500;
int n;
int a[N];
vector<int> forX[N];
int b[N];
int lst[N];
int main()
{
startTime = clock();
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
a[i]--;
forX[a[i]].push_back(i);
}
for (int i = 0; i <= n; i++)
b[i] = n;
for (int x = 0; x < n; x++) {
for (int i = 3; i < (int)forX[x].size(); i++) {
b[forX[x][i - 3]] = min(b[forX[x][i - 3]], forX[x][i]);
}
}
for (int i = n - 1; i >= 0; i--)
b[i] = min(b[i], b[i + 1]);
// for (int i = 0; i <= n; i++)
// eprintf("%d ", b[i]);
// eprintf("\n");
build();
for (int i = 0; i <= n; i++)
addSegm(1, i, i + 1, -i);
ll ans = 0;
for (int x = 0; x < n; x++)
lst[x] = n;
for (int i = n - 1; i >= 0; i--) {
int x = a[i];
addSegm(1, i + 1, lst[x] + 1, 3);
lst[x] = i;
pii val = getMin(1, i + 1, b[i] + 1);
// eprintf("%d %d %d\n", i, val.first, val.second);
if (val.first == -i) ans += val.second;
}
printf("%lld\n", ans);
return 0;
}
8-_-8
使用了线段树。
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ii pair <int, int>
#define app push_back
#define all(a) a.begin(), a.end()
#define bp __builtin_popcountll
#define ll long long
#define mp make_pair
#define f first
#define s second
#define Time (double)clock()/CLOCKS_PER_SEC
#define debug(x) std::cout << #x << ": " << x << '\n';
const int N = 1e6+7;
int cur[N];
int n;
ii mx[N << 2];
int prop[N << 2];
void relax(int v) {
if (mx[v * 2 + 1].f == mx[v * 2 + 2].f) {
mx[v] = mx[v * 2 + 1];
mx[v].s += mx[v * 2 + 2].s;
}
else {
mx[v] = max(mx[v * 2 + 1], mx[v * 2 + 2]);
}
}
void gap(int v, int x) {
mx[v].f += x;
prop[v] += x;
}
void push(int v) {
gap(v * 2 + 1, prop[v]);
gap(v * 2 + 2, prop[v]);
prop[v] = 0;
}
void add(int v, int tl, int tr, int l, int r, int x) {
if (tr < l || r < tl)
return;
if (l <= tl && tr <= r) {
gap(v, x);
return;
}
int tm = (tl + tr) >> 1;
push(v);
add(v * 2 + 1, tl, tm, l, r, x);
add(v * 2 + 2, tm + 1, tr, l, r, x);
relax(v);
}
void build(int v, int tl, int tr) {
mx[v].s = tr - tl + 1;
if (tl == tr)
return;
int tm = (tl + tr) >> 1;
build(v * 2 + 1, tl, tm);
build(v * 2 + 2, tm + 1, tr);
}
/*
void add(int l, int r, int x) {
for (int i = l; i <= r; ++i)
cur[i] += x;
}
ii get_max() {
ii ans = mp(0, 0);
for (int i = 0; i < n; ++i) {
if (cur[i] > ans.f)
ans = mp(cur[i], 1);
else if (cur[i] == ans.f)
ans.s++;
}
return ans;
}
*/
void add(int l, int r, int x) {
add(0, 0, n - 1, l, r, x);
}
signed main() {
#ifdef HOME
freopen("input.txt", "r", stdin);
#else
#define endl '\n'
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cout.setf(ios::fixed); cout.precision(20);
#endif
cin >> n;
vector <int> a(n);
vector <vector <int> > pos(n + 1);
for (int i = 0; i < n; ++i) {
cin >> a[i];
pos[a[i]].app(i);
}
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < 5; ++j) {
pos[i].app(n);
}
}
build(0, 0, n - 1);
for (int i = 1; i <= n; ++i) {
add(0, pos[i][0] - 1, 1);
add(pos[i][2], pos[i][3] - 1, 1);
}
vector <int> ptr(n + 1);
int ans = 0;
for (int l = 0; l < n; ++l) {
if (l) {
int x = a[l - 1];
//
add(l, pos[x][ptr[x]] - 1, -1);
add(pos[x][ptr[x]+2], pos[x][ptr[x]+3]-1, -1);
ptr[x]++;
add(l, pos[x][ptr[x]] - 1, 1);
add(pos[x][ptr[x]+2], pos[x][ptr[x]+3]-1, 1);
}
ii t = mx[0];
if (t.f == n)
ans += t.s;
}
cout << ans << endl;
}