比赛记录 【Educational Codeforces Round 94】
Educational Codeforces Round 94
A. String Similarity
方法 1
比赛时使用的方法。
下面记子段
考虑分别取
注意到这其实是要取
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;
char s[MAXN];
void solve(void)
{
int n;
scanf("%d%s",&n,s+1);
for(int i=1; i<=2*n-1; i+=2) putchar(s[i]);
putchar('\n');
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--) solve();
return 0;
}
方法 2
注意到所有子段都包含
Code
by tmwilliamlin168
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define ar array
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <typename T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define vt vector
#define pb push_back
#define all(c) (c).begin(), (c).end()
#define sz(x) (int)(x).size()
#define F_OR(i, a, b, s) for (int i=(a); (s)>0?i<(b):i>(b); i+=(s))
#define F_OR1(e) F_OR(i, 0, e, 1)
#define F_OR2(i, e) F_OR(i, 0, e, 1)
#define F_OR3(i, b, e) F_OR(i, b, e, 1)
#define F_OR4(i, b, e, s) F_OR(i, b, e, s)
#define GET5(a, b, c, d, e, ...) e
#define F_ORC(...) GET5(__VA_ARGS__, F_OR4, F_OR3, F_OR2, F_OR1)
#define FOR(...) F_ORC(__VA_ARGS__)(__VA_ARGS__)
#define EACH(x, a) for (auto& x: a)
template<class T> bool umin(T& a, const T& b) {
return b<a?a=b, 1:0;
}
template<class T> bool umax(T& a, const T& b) {
return a<b?a=b, 1:0;
}
ll FIRSTTRUE(function<bool(ll)> f, ll lb, ll rb) {
while(lb<rb) {
ll mb=(lb+rb)/2;
f(mb)?rb=mb:lb=mb+1;
}
return lb;
}
ll LASTTRUE(function<bool(ll)> f, ll lb, ll rb) {
while(lb<rb) {
ll mb=(lb+rb+1)/2;
f(mb)?lb=mb:rb=mb-1;
}
return lb;
}
template<class A> void read(vt<A>& v);
template<class A, size_t S> void read(ar<A, S>& a);
template<class T> void read(T& x) {
cin >> x;
}
void read(double& d) {
string t;
read(t);
d=stod(t);
}
void read(long double& d) {
string t;
read(t);
d=stold(t);
}
template<class H, class... T> void read(H& h, T&... t) {
read(h);
read(t...);
}
template<class A> void read(vt<A>& x) {
EACH(a, x)
read(a);
}
template<class A, size_t S> void read(array<A, S>& x) {
EACH(a, x)
read(a);
}
string to_string(char c) {
return string(1, c);
}
string to_string(bool b) {
return b?"true":"false";
}
string to_string(const char* s) {
return string(s);
}
string to_string(string s) {
return s;
}
string to_string(vt<bool> v) {
string res;
FOR(sz(v))
res+=char('0'+v[i]);
return res;
}
template<size_t S> string to_string(bitset<S> b) {
string res;
FOR(S)
res+=char('0'+b[i]);
return res;
}
template<class T> string to_string(T v) {
bool f=1;
string res;
EACH(x, v) {
if(!f)
res+=' ';
f=0;
res+=to_string(x);
}
return res;
}
template<class A> void write(A x) {
cout << to_string(x);
}
template<class H, class... T> void write(const H& h, const T&... t) {
write(h);
write(t...);
}
void print() {
write("\n");
}
template<class H, class... T> void print(const H& h, const T&... t) {
write(h);
if(sizeof...(t))
write(' ');
print(t...);
}
void DBG() {
cerr << "]" << endl;
}
template<class H, class... T> void DBG(H h, T... t) {
cerr << to_string(h);
if(sizeof...(t))
cerr << ", ";
DBG(t...);
}
#ifdef _DEBUG
#define dbg(...) cerr << "LINE(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
#else
#define dbg(...) 0
#endif
template<class T> void offset(ll o, T& x) {
x+=o;
}
template<class T> void offset(ll o, vt<T>& x) {
EACH(a, x)
offset(o, a);
}
template<class T, size_t S> void offset(ll o, ar<T, S>& x) {
EACH(a, x)
offset(o, a);
}
mt19937 mt_rng(chrono::steady_clock::now().time_since_epoch().count());
ll randint(ll a, ll b) {
return uniform_int_distribution<ll>(a, b)(mt_rng);
}
template<class T, class U> void vti(vt<T> &v, U x, size_t n) {
v=vt<T>(n, x);
}
template<class T, class U> void vti(vt<T> &v, U x, size_t n, size_t m...) {
v=vt<T>(n);
EACH(a, v)
vti(a, x, m);
}
const int d4i[4]={-1, 0, 1, 0}, d4j[4]={0, 1, 0, -1};
const int d8i[8]={-1, -1, 0, 1, 1, 1, 0, -1}, d8j[8]={0, 1, 1, 1, 0, -1, -1, -1};
void solve() {
int n;
string s;
read(n, s);
FOR(n)
write(s[n-1]);
print();
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t=1;
read(t);
FOR(t) {
//write("Case #", i+1, ": ");
solve();
}
}
B. RPG Protagonist
不妨假设
考虑枚举自己带的剑的数量,剩下的剑让随从尽可能多地带。然后两个人带尽可能多的斧头即可。
My Code
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
void solve(void)
{
int p,f,cs,cw,s,w;
scanf("%d%d%d%d%d%d",&p,&f,&cs,&cw,&s,&w);
if(s>w){ swap(s,w); swap(cs,cw);}
int ans = 0;
for(int i=0; i<=cs && i<=p/s; ++i)
{
int x = min((p - i*s)/w, cw);
int res = i + x;
int y = min(f/s, cs - i);
res += y + min((f - (y * s))/w, cw-x);
ans = max(ans, res);
}
printf("%d\n",ans);
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--) solve();
return 0;
}
C. Binary String Reconstruction
注意到若
将
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 = 1e5 + 5;
char s[MAXN];
void solve(void)
{
int x;
scanf("%s%d",s+1,&x);
int n = strlen(s+1);
static int a[MAXN];
for(int i=1; i<=n; ++i) a[i] = 1;
for(int i=1; i<=n; ++i) if(s[i] == '0')
{
if(i-x >= 1) a[i-x] = 0;
if(i+x <= n) a[i+x] = 0;
}
for(int i=1; i<=n; ++i) if(s[i] == '1')
{
bool flag = 0;
if(i-x >= 1 && a[i-x]) flag = 1;
if(i+x <= n && a[i+x]) flag = 1;
if(!flag)
{
printf("-1\n");
return;
}
}
for(int i=1; i<=n; ++i) putchar(a[i] + '0');
putchar('\n');
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--) solve();
return 0;
}
D. Zigzags
方法 1
比赛时使用的方法。
考虑枚举
考虑固定
将
维护两个桶
一开始,
将
My Code
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 3e3 + 5;
int a[MAXN];
void solve(void)
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
ll ans = 0;
for(int i=1; i<=n; ++i)
{
static int cntl[MAXN], cntr[MAXN];
for(int j=1; j<=n; ++j) cntl[j] = cntr[j] = 0;
for(int j=i+2; j<=n; ++j) ++cntr[a[j]];
ll cur = 0;
for(int j=i+1; j<n; ++j)
{
if(a[j] == a[i]) ans += cur;
cur -= cntl[a[j+1]]; --cntr[a[j+1]];
cur += cntr[a[j]]; ++cntl[a[j]];
}
}
printf("%lld\n",ans);
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--) solve();
return 0;
}
方法 2
考虑计算二元组
从大到小枚举
然后枚举
这种方法不但容易理解,而且代码简短,不易出错。
Code
neal
用的是方法 2。
学习到的技巧和知识
freq是作为桶的一个很好的变量名。
#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
void run_case() {
int N;
cin >> N;
vector<int> A(N);
for (auto &a : A) {
cin >> a;
a--;
}
vector<int> freq(N * N, 0);
int64_t total = 0;
for (int k = N - 1; k >= 0; k--) {
for (int l = k + 1; l < N; l++)
freq[A[k] * N + A[l]]++;
int j = k - 1;
for (int i = 0; i < j; i++)
total += freq[A[i] * N + A[j]];
}
cout << total << '\n';
}
int main() {
ios::sync_with_stdio(false);
#ifndef NEAL_DEBUG
cin.tie(nullptr);
#endif
int tests;
cin >> tests;
while (tests-- > 0)
run_case();
}
tmwilliamlin168
用的是方法 1。
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define ar array
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <typename T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define vt vector
#define pb push_back
#define all(c) (c).begin(), (c).end()
#define sz(x) (int)(x).size()
#define F_OR(i, a, b, s) for (int i=(a); (s)>0?i<(b):i>(b); i+=(s))
#define F_OR1(e) F_OR(i, 0, e, 1)
#define F_OR2(i, e) F_OR(i, 0, e, 1)
#define F_OR3(i, b, e) F_OR(i, b, e, 1)
#define F_OR4(i, b, e, s) F_OR(i, b, e, s)
#define GET5(a, b, c, d, e, ...) e
#define F_ORC(...) GET5(__VA_ARGS__, F_OR4, F_OR3, F_OR2, F_OR1)
#define FOR(...) F_ORC(__VA_ARGS__)(__VA_ARGS__)
#define EACH(x, a) for (auto& x: a)
template<class T> bool umin(T& a, const T& b) {
return b<a?a=b, 1:0;
}
template<class T> bool umax(T& a, const T& b) {
return a<b?a=b, 1:0;
}
ll FIRSTTRUE(function<bool(ll)> f, ll lb, ll rb) {
while(lb<rb) {
ll mb=(lb+rb)/2;
f(mb)?rb=mb:lb=mb+1;
}
return lb;
}
ll LASTTRUE(function<bool(ll)> f, ll lb, ll rb) {
while(lb<rb) {
ll mb=(lb+rb+1)/2;
f(mb)?lb=mb:rb=mb-1;
}
return lb;
}
template<class A> void read(vt<A>& v);
template<class A, size_t S> void read(ar<A, S>& a);
template<class T> void read(T& x) {
cin >> x;
}
void read(double& d) {
string t;
read(t);
d=stod(t);
}
void read(long double& d) {
string t;
read(t);
d=stold(t);
}
template<class H, class... T> void read(H& h, T&... t) {
read(h);
read(t...);
}
template<class A> void read(vt<A>& x) {
EACH(a, x)
read(a);
}
template<class A, size_t S> void read(array<A, S>& x) {
EACH(a, x)
read(a);
}
string to_string(char c) {
return string(1, c);
}
string to_string(bool b) {
return b?"true":"false";
}
string to_string(const char* s) {
return string(s);
}
string to_string(string s) {
return s;
}
string to_string(vt<bool> v) {
string res;
FOR(sz(v))
res+=char('0'+v[i]);
return res;
}
template<size_t S> string to_string(bitset<S> b) {
string res;
FOR(S)
res+=char('0'+b[i]);
return res;
}
template<class T> string to_string(T v) {
bool f=1;
string res;
EACH(x, v) {
if(!f)
res+=' ';
f=0;
res+=to_string(x);
}
return res;
}
template<class A> void write(A x) {
cout << to_string(x);
}
template<class H, class... T> void write(const H& h, const T&... t) {
write(h);
write(t...);
}
void print() {
write("\n");
}
template<class H, class... T> void print(const H& h, const T&... t) {
write(h);
if(sizeof...(t))
write(' ');
print(t...);
}
void DBG() {
cerr << "]" << endl;
}
template<class H, class... T> void DBG(H h, T... t) {
cerr << to_string(h);
if(sizeof...(t))
cerr << ", ";
DBG(t...);
}
#ifdef _DEBUG
#define dbg(...) cerr << "LINE(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
#else
#define dbg(...) 0
#endif
template<class T> void offset(ll o, T& x) {
x+=o;
}
template<class T> void offset(ll o, vt<T>& x) {
EACH(a, x)
offset(o, a);
}
template<class T, size_t S> void offset(ll o, ar<T, S>& x) {
EACH(a, x)
offset(o, a);
}
mt19937 mt_rng(chrono::steady_clock::now().time_since_epoch().count());
ll randint(ll a, ll b) {
return uniform_int_distribution<ll>(a, b)(mt_rng);
}
template<class T, class U> void vti(vt<T> &v, U x, size_t n) {
v=vt<T>(n, x);
}
template<class T, class U> void vti(vt<T> &v, U x, size_t n, size_t m...) {
v=vt<T>(n);
EACH(a, v)
vti(a, x, m);
}
const int d4i[4]={-1, 0, 1, 0}, d4j[4]={0, 1, 0, -1};
const int d8i[8]={-1, -1, 0, 1, 1, 1, 0, -1}, d8j[8]={0, 1, 1, 1, 0, -1, -1, -1};
void solve() {
int n;
read(n);
vt<int> a(n);
read(a);
offset(-1, a);
ll ans=0;
FOR(n) {
vt<int> cl(n), cr(n);
int ca=0;
FOR(j, i+1, n)
++cr[a[j]];
FOR(j, i+1, n) {
--cr[a[j]];
ca-=cl[a[j]];
if(a[j]==a[i])
ans+=ca;
++cl[a[j]];
ca+=cr[a[j]];
}
}
print(ans);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t=1;
read(t);
FOR(t) {
//write("Case #", i+1, ": ");
solve();
}
}
E. Clear the Multiset
方法 1
为方便描述,下称 “将区间
考虑分治,
- 直接使用操作 2 依次将
[l,r] 中的每个数清零,这需要耗费的最小次数,即为[l,r] 中大于del 的数的个数。 - 设
[l,r] 的最小值为mn ,使用操作 1 将[l,r] 的数都减小mn-del 。设最小值的位置为pos ,则最小操作次数为mn-del + solve(l,pos-1,mn) + solve(pos+1,r,mn) 。
这两种情况取较小值即为
最终结果是
在实际实现中,可以分成三种情况来简化计算:
-
- 不管每个数的具体值,直接使用操作 2 将
[l,r] 中的数清零,此时需要r-l+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 = 5e3 + 5;
int a[MAXN];
ll solve(int l,int r, int done)
{
if(l>r) return 0;
bool flag = 0;
for(int i=l; i<=r; ++i)
if(a[i] > done){ flag=1; break;}
if(!flag) return 0;
if(l==r) return 1;
int mn = l;
for(int i=l; i<=r; ++i)
if(a[i] < a[mn]) mn = i;
return min(a[mn] - done + solve(l,mn-1, a[mn]) + solve(mn+1,r, a[mn]), (ll)r-l+1);
}
int main(void)
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
printf("%lld\n",solve(1,n,0));
return 0;
}
方法 2.1
为方便描述,下称 “将区间
设
边界情况是
考虑枚举
设
于是这个
对所有的
这个
考虑最终的结果,只需要设
方法 2.2
注意到这个
按
因为单调栈中的每个点,都有一个以这个点为
即,设
注意到第一种情况涉及到的点,就是要被弹出单调栈的点。下面记
维护单调栈中所有元素的
下面看第二种情况,设
对于每个弹出栈的元素
在压入
时间复杂度是
My Code
因为此题
#include<cstdio>
#include<algorithm>
#include<vector>
#include<stack>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 5e3 + 5;
const ll linf = 0x3f3f3f3f3f3f3f3f;
struct State
{
int a;
ll f,g;
};
int a[MAXN];
ll dp[MAXN];
int main(void)
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
a[++n] = 0;
stack<State> sta;
sta.push((State){0,0,0});
for(int i=1; i<=n; ++i)
{
dp[i] = linf;
ll g = linf;
while(!sta.empty() && sta.top().a >= a[i])
{
dp[i] = min(dp[i], sta.top().f + i - 1);
g = min(g, sta.top().f);
sta.pop();
}
g -= a[i];
if(!sta.empty())
g = min(g, sta.top().g),
dp[i] = min(dp[i], sta.top().g + i - 1 + a[i]);
g = min(g, dp[i] - i - a[i]);
sta.push((State){a[i], dp[i]-i, g});
}
printf("%lld\n",dp[n]);
return 0;
}
Code
neal
用了方法 1。
学习到的技巧和知识
max_element和min_element的应用。
#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
int N;
vector<int> A;
int solve(int first, int last) {
int outside = max(A[first - 1], A[last + 1]);
if (first > last || *max_element(A.begin() + first, A.begin() + last + 1) <= outside)
return 0;
int best = last - first + 1;
int minimum = *min_element(A.begin() + first, A.begin() + last + 1);
assert(minimum >= outside);
int start = first;
int option = minimum - outside;
for (int i = first; i <= last; i++)
if (A[i] == minimum) {
option += solve(start, i - 1);
start = i + 1;
}
option += solve(start, last);
best = min(best, option);
return best;
}
int main() {
ios::sync_with_stdio(false);
#ifndef NEAL_DEBUG
cin.tie(nullptr);
#endif
cin >> N;
A.assign(N + 2, 0);
for (int i = 1; i <= N; i++)
cin >> A[i];
cout << solve(1, N) << '\n';
}
tmwilliamlin168
选择的是方法 2.1。
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define ar array
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <typename T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define vt vector
#define pb push_back
#define all(c) (c).begin(), (c).end()
#define sz(x) (int)(x).size()
#define F_OR(i, a, b, s) for (int i=(a); (s)>0?i<(b):i>(b); i+=(s))
#define F_OR1(e) F_OR(i, 0, e, 1)
#define F_OR2(i, e) F_OR(i, 0, e, 1)
#define F_OR3(i, b, e) F_OR(i, b, e, 1)
#define F_OR4(i, b, e, s) F_OR(i, b, e, s)
#define GET5(a, b, c, d, e, ...) e
#define F_ORC(...) GET5(__VA_ARGS__, F_OR4, F_OR3, F_OR2, F_OR1)
#define FOR(...) F_ORC(__VA_ARGS__)(__VA_ARGS__)
#define EACH(x, a) for (auto& x: a)
template<class T> bool umin(T& a, const T& b) {
return b<a?a=b, 1:0;
}
template<class T> bool umax(T& a, const T& b) {
return a<b?a=b, 1:0;
}
ll FIRSTTRUE(function<bool(ll)> f, ll lb, ll rb) {
while(lb<rb) {
ll mb=(lb+rb)/2;
f(mb)?rb=mb:lb=mb+1;
}
return lb;
}
ll LASTTRUE(function<bool(ll)> f, ll lb, ll rb) {
while(lb<rb) {
ll mb=(lb+rb+1)/2;
f(mb)?lb=mb:rb=mb-1;
}
return lb;
}
template<class A> void read(vt<A>& v);
template<class A, size_t S> void read(ar<A, S>& a);
template<class T> void read(T& x) {
cin >> x;
}
void read(double& d) {
string t;
read(t);
d=stod(t);
}
void read(long double& d) {
string t;
read(t);
d=stold(t);
}
template<class H, class... T> void read(H& h, T&... t) {
read(h);
read(t...);
}
template<class A> void read(vt<A>& x) {
EACH(a, x)
read(a);
}
template<class A, size_t S> void read(array<A, S>& x) {
EACH(a, x)
read(a);
}
string to_string(char c) {
return string(1, c);
}
string to_string(bool b) {
return b?"true":"false";
}
string to_string(const char* s) {
return string(s);
}
string to_string(string s) {
return s;
}
string to_string(vt<bool> v) {
string res;
FOR(sz(v))
res+=char('0'+v[i]);
return res;
}
template<size_t S> string to_string(bitset<S> b) {
string res;
FOR(S)
res+=char('0'+b[i]);
return res;
}
template<class T> string to_string(T v) {
bool f=1;
string res;
EACH(x, v) {
if(!f)
res+=' ';
f=0;
res+=to_string(x);
}
return res;
}
template<class A> void write(A x) {
cout << to_string(x);
}
template<class H, class... T> void write(const H& h, const T&... t) {
write(h);
write(t...);
}
void print() {
write("\n");
}
template<class H, class... T> void print(const H& h, const T&... t) {
write(h);
if(sizeof...(t))
write(' ');
print(t...);
}
void DBG() {
cerr << "]" << endl;
}
template<class H, class... T> void DBG(H h, T... t) {
cerr << to_string(h);
if(sizeof...(t))
cerr << ", ";
DBG(t...);
}
#ifdef _DEBUG
#define dbg(...) cerr << "LINE(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
#else
#define dbg(...) 0
#endif
template<class T> void offset(ll o, T& x) {
x+=o;
}
template<class T> void offset(ll o, vt<T>& x) {
EACH(a, x)
offset(o, a);
}
template<class T, size_t S> void offset(ll o, ar<T, S>& x) {
EACH(a, x)
offset(o, a);
}
mt19937 mt_rng(chrono::steady_clock::now().time_since_epoch().count());
ll randint(ll a, ll b) {
return uniform_int_distribution<ll>(a, b)(mt_rng);
}
template<class T, class U> void vti(vt<T> &v, U x, size_t n) {
v=vt<T>(n, x);
}
template<class T, class U> void vti(vt<T> &v, U x, size_t n, size_t m...) {
v=vt<T>(n);
EACH(a, v)
vti(a, x, m);
}
const int d4i[4]={-1, 0, 1, 0}, d4j[4]={0, 1, 0, -1};
const int d8i[8]={-1, -1, 0, 1, 1, 1, 0, -1}, d8j[8]={0, 1, 1, 1, 0, -1, -1, -1};
void solve() {
int n;
read(n);
vt<int> a(n);
read(a);
a.insert(a.begin(), 0);
a.pb(0);
vt<ll> dp(n+2);
FOR(i, 1, n+2) {
int mn=1e9;
dp[i]=1e18;
FOR(j, i-1, -1, -1) {
umin(mn, a[j]);
umin(dp[i], max(a[i]-mn, 0)+dp[j]+i-j-1);
}
}
print(dp[n+1]);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t=1;
//read(t);
FOR(t) {
//write("Case #", i+1, ": ");
solve();
}
}
F. x-prime Substrings
方法 1
注意到
提前搜索出所有的 x-prime,然后考虑 dp。
问题是如何设计状态,第一维应该是
x-prime 不会出现包含关系。在
这个状态的设计显然太 “啰嗦” 了,考虑这个状态实际上是在干什么。注意到这个 ”匹配到哪个串的哪个前缀“ 实际上就是 trie 在干的事情。
所以,将所有的 x-prime 放到 trie 上。
我们能设计出状态:
用
考虑从第
- 删除第
i+1 位,即,用dp[i][j]+1 来更新dp[i+1][j] 。 - 保留第
i+1 位,此时用dp[i][j] 来更新dp[i+1][k] ,k 表示i+1 这个前缀对应的 trie 上的点。此时难点就在如何计算k 。
下面讲第二种转移。
为了方便描述,下面设
注意到
由于总点数和每个串的长度都很小,此过程当然可以暴力进行预处理。即预处理出
Aho-Corasick 算法
ac 自动机可以用来解决上面的问题,即如何处理出
考虑对于这棵 trie 上的每个点额外向外连一条边,点
这条边叫 suffix link,是 Aho-Corasick 算法的核心。我们设点
下面我们记点
考虑计算
考虑计算
- 点
u 有c 这个儿子。显然link[u][c] 就是这个儿子。 -
- 若
u 既没有c 这个儿子又不是根节点,那么link[u][c] = link[suff[u]][c] 。
注意到这是一个迭代计算的过程,而在这个过程中,点的深度都是不断降低的,因此不会出现循环的情况。
My Code
用 bfs 的方式处理出 suffix link。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<queue>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 1e3 + 5;
const int MAXX = 20 + 5;
const int inf = 0x3f3f3f3f;
template<const char minc='0', const int MAXD = 10>
struct Aho_Corasick
{
struct Node
{
int link[MAXD], suff;
bool leaf;
Node(void): suff(-1), leaf(0) { memset(link,-1,sizeof(link));}
};
vector<Node> p;
Aho_Corasick(void){ p.resize(1);}
Aho_Corasick(const vector<string> &vec){ p.resize(1); build(vec);}
inline void clear(void){ p.resize(1);}
inline int size(void){ return (int)p.size();}
void insert(const string &s)
{
int u = 0;
for(int i=0; i<(int)s.size(); ++i)
{
if(p[u].link[s[i] - minc] == -1)
p[u].link[s[i] - minc] = (int)p.size(),
p.push_back(Node());
u = p[u].link[s[i] - minc];
}
p[u].leaf = 1;
}
void build(void)
{
queue<int> q;
p[0].suff = 0;
q.push(0);
while(!q.empty())
{
int u = q.front(); q.pop();
for(int i=0; i<MAXD; ++i)
{
int &v = p[u].link[i];
if(~v)
p[v].suff = u? p[p[u].suff].link[i]: 0,
q.push(v);
else v = u? p[p[u].suff].link[i]: 0;
}
}
}
void build(const vector<string> &vec)
{
for(int i=0; i<(int)vec.size(); ++i)
insert(vec[i]);
build();
}
inline bool is_leaf(int u){ return p[u].leaf;}
inline int link(int u, char c){ return p[u].link[c-minc];}
};
int x;
char a[MAXX];
inline bool check(int pos)
{
for(int i=1; i<pos; ++i)
{
int sum = 0;
for(int j=i; j<pos; ++j)
{
sum += a[j] - '0';
if(sum<x && x%sum==0) return 0;
}
}
return 1;
}
Aho_Corasick<'0',10> ac_auto;
void dfs(int sum,int pos)
{
if(sum>x) return;
if(sum == x){ if(check(pos)) ac_auto.insert(string(a+1,a+pos)); return;}
for(int i=1; i<=9 && sum+i<=x; ++i)
a[pos] = i + '0',
dfs(sum+i, pos+1);
}
char s[MAXN];
int main(void)
{
scanf("%s%d",s+1,&x);
int n = strlen(s+1);
dfs(0,1);
ac_auto.build();
int tot = ac_auto.size();
vector<int> dp(tot, inf);
dp[0] = 0;
for(int i=1; i<=n; ++i)
{
vector<int> ndp(tot, inf);
for(int j=0; j<tot; ++j) if(dp[j] != inf)
{
ndp[j] = min(ndp[j], dp[j] + 1);
int k = ac_auto.link(j, s[i]);
if(!ac_auto.is_leaf(k))
ndp[k] = min(ndp[k], dp[j]);
}
dp = ndp;
}
printf("%d",*min_element(dp.begin(), dp.end()));
return 0;
}
Code
neal
这份代码的变量名十分清晰,ac 自动机的每个函数旁都有对应的注释。
#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
// This version of aho_corasick uses more memory and depends on a small alphabet, but it provides O(1) suffix links.
template<char MIN_CHAR = 'a', int ALPHABET = 26>
struct aho_corasick {
struct node {
// suff = the index of the node of the longest strict suffix of the current node that's also in the tree.
// Also see "blue arcs" on Wikipedia: https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm
// dict = the index of the node of the longest strict suffix of the current node that's in the word list.
// Also see "green arcs" on Wikipedia.
// depth = normal trie depth (root is 0). Can be removed to save memory.
// word_index = the index of the *first* word ending at this node. -1 if none.
// word_count = the total number of words ending at this node. Used in count_total_matches().
// link = the trie connections and/or suffix connections from this node.
int suff = -1, dict = -1, depth = 0;
int word_index = -1, word_count = 0;
int link[ALPHABET];
node() {
fill(link, link + ALPHABET, -1);
}
int& operator[](char c) {
return link[c - MIN_CHAR];
}
};
vector<node> nodes;
int W;
vector<int> word_location;
vector<int> word_indices_by_depth;
vector<int> defer;
aho_corasick(const vector<string> &words = {}) {
if (!words.empty())
build(words);
}
// Builds the adj list based on suffix parents. Often we want to perform DP and/or queries on this tree.
vector<vector<int>> build_suffix_adj() const {
vector<vector<int>> adj(nodes.size());
for (int i = 1; i < int(nodes.size()); i++)
adj[nodes[i].suff].push_back(i);
return adj;
}
int get_or_add_child(int current, char c) {
if (nodes[current][c] >= 0)
return nodes[current][c];
int index = int(nodes.size());
nodes[current][c] = index;
nodes.emplace_back();
nodes.back().depth = nodes[current].depth + 1;
return index;
}
int add_word(const string &word, int word_index) {
assert(!nodes.empty());
int current = 0;
for (char c : word)
current = get_or_add_child(current, c);
if (nodes[current].word_index < 0)
nodes[current].word_index = word_index;
nodes[current].word_count++;
return current;
}
// Returns where in the trie we should end up after starting at `location` and adding char `c`. Runs in O(1).
int get_suffix_link(int location, char c) const {
if (location >= 0)
location = nodes[location].link[c - MIN_CHAR];
return max(location, 0);
}
void build(const vector<string> &words) {
nodes = {node()};
W = int(words.size());
word_location.resize(W);
defer.resize(W);
int max_depth = 0;
for (int i = 0; i < W; i++) {
word_location[i] = add_word(words[i], i);
max_depth = max(max_depth, int(words[i].size()));
defer[i] = nodes[word_location[i]].word_index;
}
// Create a list of word indices in decreasing order of depth, in linear time via counting sort.
word_indices_by_depth.resize(W);
vector<int> depth_freq(max_depth + 1, 0);
for (int i = 0; i < W; i++)
depth_freq[words[i].size()]++;
for (int i = max_depth - 1; i >= 0; i--)
depth_freq[i] += depth_freq[i + 1];
for (int i = 0; i < W; i++)
word_indices_by_depth[--depth_freq[words[i].size()]] = i;
// Solve suffix parents by traversing in order of depth (BFS order).
vector<int> q = {0};
for (int i = 0; i < int(q.size()); i++) {
int current = q[i];
for (char c = MIN_CHAR; c < MIN_CHAR + ALPHABET; c++) {
int &index = nodes[current][c];
if (index >= 0) {
// Find index's suffix parent by traversing suffix parents of current until one of them has a child c.
int suffix_parent = get_suffix_link(nodes[current].suff, c);
nodes[index].suff = suffix_parent;
nodes[index].word_count += nodes[suffix_parent].word_count;
nodes[index].dict = nodes[suffix_parent].word_index < 0 ? nodes[suffix_parent].dict : suffix_parent;
q.push_back(index);
} else {
index = get_suffix_link(nodes[current].suff, c);
}
}
}
}
// Counts the number of matches of each word in O(text length + num words).
vector<int> count_matches(const string &text) const {
vector<int> matches(W, 0);
int current = 0;
for (char c : text) {
current = get_suffix_link(current, c);
int dict_node = nodes[current].word_index < 0 ? nodes[current].dict : current;
if (dict_node >= 0)
matches[nodes[dict_node].word_index]++;
}
// Iterate in decreasing order of depth.
for (int word_index : word_indices_by_depth) {
int location = word_location[word_index];
int dict_node = nodes[location].dict;
if (dict_node >= 0)
matches[nodes[dict_node].word_index] += matches[word_index];
}
for (int i = 0; i < W; i++)
matches[i] = matches[defer[i]];
return matches;
}
// Counts the number of matches over all words at each ending position in `text` in O(text length).
vector<int> count_matches_by_position(const string &text) const {
vector<int> matches(text.size());
int current = 0;
for (int i = 0; i < int(text.size()); i++) {
current = get_suffix_link(current, text[i]);
matches[i] = nodes[current].word_count;
}
return matches;
}
// Counts the total number of matches of all words within `text` in O(text length).
int64_t count_total_matches(const string &text) const {
int64_t matches = 0;
int current = 0;
for (char c : text) {
current = get_suffix_link(current, c);
matches += nodes[current].word_count;
}
return matches;
}
};
const int INF = 1e9 + 5;
int N, X;
string S;
vector<string> prime;
aho_corasick<'1', 9> AC;
bool check(string str) {
int n = int(str.size());
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += str[j] - '0';
if (sum < X && X % sum == 0)
return false;
}
}
return true;
}
void generate(string str, int sum) {
if (sum > X)
return;
if (sum == X) {
if (check(str))
prime.push_back(str);
return;
}
for (int d = 1; d <= 9 && sum + d <= X; d++)
generate(str + char(d + '0'), sum + d);
}
int main() {
ios::sync_with_stdio(false);
#ifndef NEAL_DEBUG
cin.tie(nullptr);
#endif
cin >> S >> X;
N = int(S.size());
generate("", 0);
dbg(prime);
AC.build(prime);
int ST = int(AC.nodes.size());
vector<int> dp(ST, INF);
dp[0] = 0;
for (auto &ch : S) {
vector<int> next_dp(ST, INF);
for (int state = 0; state < ST; state++)
if (dp[state] < INF) {
next_dp[state] = min(next_dp[state], dp[state] + 1);
int transition = AC.get_suffix_link(state, ch);
if (AC.nodes[transition].word_index < 0)
next_dp[transition] = min(next_dp[transition], dp[state]);
}
swap(dp, next_dp);
}
cout << *min_element(dp.begin(), dp.end()) << '\n';
}
krijgertje
直接暴力预处理每个节点加上每个数字后,跳到的节点。适度使用了 stl 使程序更加清晰。
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <list>
#include <cassert>
#include <climits>
#include <bitset>
#include <chrono>
#include <random>
using namespace std;
#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n) FORE(i,0,n)
#define FORSZ(i,a,v) FOR(i,a,SZ(v))
#define REPSZ(i,v) REP(i,SZ(v))
std::mt19937 rnd((int)std::chrono::steady_clock::now().time_since_epoch().count());
typedef long long ll;
ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }
const int MAXLEN = 1000;
char s[MAXLEN + 1]; int slen;
int x;
map<string, int> mp;
vector<string> lst;
vector<vector<int>> trans;
set<string> forbidden;
void gen() {
lst.clear(); mp.clear(); forbidden.clear();
queue<string> q;
q.push("");
while (!q.empty()) {
string s = q.front(); q.pop();
lst.PB(s); mp[s] = SZ(lst) - 1;
int sum = 0; REPSZ(i, s) sum += s[i] - '0';
FORE(d, 1, 9) if (sum + d <= x) {
int cur = d;
bool ok = true;
for (int i = SZ(s); i >= 0; --i) {
if (i < SZ(s)) cur += s[i] - '0';
if (cur < x && x % cur == 0) ok = false;
}
if (!ok) continue;
string ns = s + string(1, '0' + d);
if (sum + d == x) forbidden.insert(ns); else q.push(ns);
}
}
//printf("%d: %d %d\n", x, SZ(lst), SZ(forbidden));
trans = vector<vector<int>>(SZ(lst), vector<int>(10, -1));
REPSZ(i, lst) FORE(d, 1, 9) {
string ns = lst[i] + string(1, '0' + d);
while(true) {
if (forbidden.count(ns)) break;
if (mp.count(ns)) { trans[i][d] = mp[ns]; break; }
ns = ns.substr(1);
}
}
//REPSZ(i, lst) { printf("'%s':", lst[i].c_str()); FORE(d, 1, 9) if (trans[i][d] == -1) printf(" X"); else printf(" '%s'", lst[trans[i][d]].c_str()); puts(""); }
}
vector<int> dp[MAXLEN + 1];
int solve() {
gen();
REPE(i, slen) dp[i] = vector<int>(SZ(lst), INT_MAX);
dp[0][mp[""]] = 0;
REPE(i, slen) REPSZ(j, lst) if (dp[i][j] != INT_MAX) {
//printf("dp[%d][%d]=%d\n", i, j, dp[i][j]);
if (i == slen) continue;
int d = s[i] - '0', nj = trans[j][d];
dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + 1);
if (nj != -1) dp[i + 1][nj] = min(dp[i + 1][nj], dp[i][j] + 0);
}
int ret = INT_MAX; REPSZ(j, lst) ret = min(ret, dp[slen][j]); return ret;
}
void run() {
scanf("%s", s); slen = strlen(s);
scanf("%d", &x);
printf("%d\n", solve());
}
int main() {
run();
return 0;
}
方法 2
考虑使用状压 dp。注意到