跳到正文

个人记录

比赛记录 【Codeforces Round #658 (Div. 1)】

He_Ren约 68 分钟
原文
文章信息与版本

文章信息

发布
2020年7月22日
收录
2026年7月7日
更新
2026年11月13日
篇幅
约 68 分钟
获赞
2

版本

  1. v1当前

Codeforces Round #658 (Div. 1)

这次比赛打得不好,A 题花费了太多时间,导致 C 题没有时间做。但比赛结束后也花了比较长的时间才把 C 题 A 掉,还 WA 了很多次。所以总的来说还是能力出了问题。

A. Prefix Flip

考虑倒序匹配 aa 和 bb,对于当前匹配到的 aia_i 和 bib_i 考虑如下策略:

  • 如果相等,直接跳过。
  • 否则,如果 a1≠bia_1 \neq b_i,那么可以通过翻转长度为 ii 的前缀使得 bib_i 得到匹配。
  • 如果 a1=bia_1 = b_i,那么可以先翻转长度为 11 的前缀,使得 a1≠bia_1 \neq b_i,然后翻转长度为 ii 的前缀。

对于每个 ii,最多进行两次翻转,所以总翻转次数一定小于等于 2n2n。

剩下的就是细节问题了。考虑记录当前的实际的 ii 对应的 aa 中的位置 nownow,再记录当前实际的第一个位置对应 aa 中的位置 firfir,再记录 revrev 表示当前的值是否翻转过即可。

My Code

由于对翻转的处理有问题,我重构了一次代码,又调试了很长时间。导致 A 题花费的时间太长,实在是不应该。

C++
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 1e5 + 5;

char s[MAXN], t[MAXN];
bool rev;

vector<int> ans;

void solve(void)
{
	int n;
	scanf("%d%s%s",&n,s+1,t+1);
	for(int i=1; i<=n; ++i)
		s[i] -= '0',
		t[i] -= '0';
	
	ans.clear();
	rev = 0;
	int fir = 1, now = n;
	for(int i=n; i>1; --i)
	{
		int sx = s[now] ^ rev;
		if(sx == t[i])
		{
			if(rev) ++now;
			else --now;
			continue;
		}
		
		if((s[fir]^rev) == t[i]) ans.push_back(1), s[fir]^=1;
		rev^=1; ans.push_back(i); swap(now, fir);
		
		if(rev) ++now;
		else --now;
	}
	if((s[fir]^rev) != t[1]) ans.push_back(1);
	
	printf("%d ",(int)ans.size());
	for(int i=0; i<(int)ans.size(); ++i) printf("%d ",ans[i]);
	putchar('\n');
}

int main(void)
{
	int T;
	scanf("%d",&T);
	while(T--) solve();
	return 0;
}

Code

下面说的 “翻转” 均为题目中所给的操作,即将长度为 ii 的前缀反转,然后将该前缀中所有数取反。

Benq

考虑正序遍历 aa 中所有元素相等的子段(下面简称 “ 子段 ” ),每次对该子段的右端点所在的前缀进行翻转。此时该前缀的所有元素,与下一个子段的元素相等。对除了最后一个子段的所有子段进行操作,此时 aa 中所有元素相等。

倒序遍历 bb 中所有子段,可以通过翻转 aa 中,该子段的右端点所在的前缀,使得 aa 中的该子段与 bb 中的该子段相等。遍历完所有子段后,aa 和 bb 就相等了。

容易发现,上述步骤进行的操作数小于等于 2n2n。

这个思路可以说是非常巧妙了,因为每次进行翻转操作时,被翻转的前缀的所有数总是相同的,这使得翻转操作可以考虑成仅仅是数值的翻转,而没有位置的翻转,这可以减少很多需要处理的细节。

还有一点就是,经过了一些操作,将 aa 中的所有数变成相等的,在后来的过程中就不用考虑输入的 aa 的具体情况了,也能减少很多需要处理的地方。

这种方法不但代码短,而且容易思考,比上述我的方法好很多。

C++
#include <bits/stdc++.h>
using namespace std;
 
typedef long long ll;
typedef long double ld;
typedef double db; 
typedef string str; 

typedef pair<int,int> pi;
typedef pair<ll,ll> pl; 
typedef pair<db,db> pd; 

typedef vector<int> vi; 
typedef vector<ll> vl; 
typedef vector<db> vd; 
typedef vector<str> vs; 
typedef vector<pi> vpi;
typedef vector<pl> vpl; 
typedef vector<pd> vpd; 

#define mp make_pair
#define f first
#define s second
#define sz(x) (int)(x).size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend() 
#define rsz resize
#define ins insert 
#define ft front() 
#define bk back()
#define pf push_front 
#define pb push_back
#define eb emplace_back 
#define lb lower_bound 
#define ub upper_bound 

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5; 
const ll INF = 1e18; 
const ld PI = acos((ld)-1);
const int xd[4] = {1,0,-1,0}, yd[4] = {0,1,0,-1}; 
mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count()); 

template<class T> bool ckmin(T& a, const T& b) { 
	return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) { 
	return a < b ? a = b, 1 : 0; } 
constexpr int pct(int x) { return __builtin_popcount(x); } 
constexpr int bits(int x) { return 31-__builtin_clz(x); } // floor(log2(x)) 
ll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } // divide a by b rounded up
ll fdiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // divide a by b rounded down
ll half(ll x) { return fdiv(x,2); }

template<class T, class U> T fstTrue(T lo, T hi, U f) {
	hi ++; assert(lo <= hi); // assuming f is increasing
	while (lo < hi) { // find first index such that f is true 
		T mid = half(lo+hi);
		f(mid) ? hi = mid : lo = mid+1; 
	} 
	return lo;
}
template<class T, class U> T lstTrue(T lo, T hi, U f) {
	lo --; assert(lo <= hi); // assuming f is decreasing
	while (lo < hi) { // find first index such that f is true 
		T mid = half(lo+hi+1);
		f(mid) ? lo = mid : hi = mid-1;
	} 
	return lo;
}
template<class T> void remDup(vector<T>& v) { 
	sort(all(v)); v.erase(unique(all(v)),end(v)); }

// INPUT
template<class A> void re(complex<A>& c);
template<class A, class B> void re(pair<A,B>& p);
template<class A> void re(vector<A>& v);
template<class A, size_t SZ> void re(array<A,SZ>& a);

template<class T> void re(T& x) { cin >> x; }
void re(db& d) { str t; re(t); d = stod(t); }
void re(ld& d) { str t; re(t); d = stold(t); }
template<class H, class... T> void re(H& h, T&... t) { re(h); re(t...); }

template<class A> void re(complex<A>& c) { A a,b; re(a,b); c = {a,b}; }
template<class A, class B> void re(pair<A,B>& p) { re(p.f,p.s); }
template<class A> void re(vector<A>& x) { trav(a,x) re(a); }
template<class A, size_t SZ> void re(array<A,SZ>& x) { trav(a,x) re(a); }

// TO_STRING
#define ts to_string
str ts(char c) { return str(1,c); }
str ts(const char* s) { return (str)s; }
str ts(str s) { return s; }
str ts(bool b) { 
	#ifdef LOCAL
		return b ? "true" : "false"; 
	#else 
		return ts((int)b);
	#endif
}
template<class A> str ts(complex<A> c) { 
	stringstream ss; ss << c; return ss.str(); }
str ts(vector<bool> v) {
	str res = "{"; F0R(i,sz(v)) res += char('0'+v[i]);
	res += "}"; return res; }
template<size_t SZ> str ts(bitset<SZ> b) {
	str res = ""; F0R(i,SZ) res += char('0'+b[i]);
	return res; }
template<class A, class B> str ts(pair<A,B> p);
template<class T> str ts(T v) { // containers with begin(), end()
	#ifdef LOCAL
		bool fst = 1; str res = "{";
		for (const auto& x: v) {
			if (!fst) res += ", ";
			fst = 0; res += ts(x);
		}
		res += "}"; return res;
	#else
		bool fst = 1; str res = "";
		for (const auto& x: v) {
			if (!fst) res += " ";
			fst = 0; res += ts(x);
		}
		return res;

	#endif
}
template<class A, class B> str ts(pair<A,B> p) {
	#ifdef LOCAL
		return "("+ts(p.f)+", "+ts(p.s)+")"; 
	#else
		return ts(p.f)+" "+ts(p.s);
	#endif
}

// OUTPUT
template<class A> void pr(A x) { cout << ts(x); }
template<class H, class... T> void pr(const H& h, const T&... t) { 
	pr(h); pr(t...); }
void ps() { pr("\n"); } // print w/ spaces
template<class H, class... T> void ps(const H& h, const T&... t) { 
	pr(h); if (sizeof...(t)) pr(" "); ps(t...); }

// DEBUG
void DBG() { cerr << "]" << endl; }
template<class H, class... T> void DBG(H h, T... t) {
	cerr << ts(h); if (sizeof...(t)) cerr << ", ";
	DBG(t...); }
#ifdef LOCAL // compile with -DLOCAL
	#define dbg(...) cerr << "LINE(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
#else
	#define dbg(...) 0
#endif

// FILE I/O
void setIn(str s) { freopen(s.c_str(),"r",stdin); }
void setOut(str s) { freopen(s.c_str(),"w",stdout); }
void unsyncIO() { ios_base::sync_with_stdio(0); cin.tie(0); }
void setIO(str s = "") {
	unsyncIO();
	// cin.exceptions(cin.failbit); 
	// throws exception when do smth illegal
	// ex. try to read letter into int
	if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
}

int n;
str a,b;

vi nor(str& x) {
	vi res;
	int ind = 0;
	while (1) {
		while (ind < n-1 && x[ind] == x[ind+1]) ind ++;
		if (ind == n-1) return res;
		res.pb(ind+1);
		x[ind] = '0'+'1'-x[ind];
	}
}

void solve() {
	re(n); re(a,b);
	vi x = nor(a);
	vi y = nor(b);
	if (a[n-1] != b[n-1]) {
		x.pb(n);
	}
	reverse(all(y)); trav(t,y) x.pb(t);
	pr(sz(x),' '); ps(x);
}

int main() {
	setIO();
	int T; re(T);
	F0R(i,T) solve();
	// you should actually read the stuff at the bottom
}

/* stuff you should look for
	* int overflow, array bounds
	* special cases (n=1?)
	* do smth instead of nothing and stay organized
	* WRITE STUFF DOWN
*/

Um_nik

为了方便起见,假设 aa 和 bb 中,11 的总数小于等于 00 的总数,显然此时 11 的个数小于等于 nn。(如果是相反的情况处理过程类似,只是把过程中的 00 换成 11 ,11 换成 00 即可)

将 aa 的所有数 11 都换成 00,方法是,从小到大遍历一遍 aa,对于每个 ai=1a_i=1,先翻转一遍长度为 i−1i-1 的前缀,此时因为所有 ii 之前的位置都已经变成 00 了,翻转之后长度为 ii 的前缀就都会变成 11。然后翻转一遍长度为 ii 的前缀,就可以将这个前缀全部变成 00 了。

然后倒序遍历 bb。对于每个 bi=1b_i=1,先翻转一遍 aa 中长度为 ii 的前缀,此时该前缀全部变为 11,然后翻转 aa 中长度为 i−1i-1 的前缀,此时,该前缀全部变为 00,而 ai=1a_i=1。

容易发现,这个方法需要的翻转次数是 11 的个数乘 22,又因为该方法保证 11 的个数小于等于 nn,所以该方法操作次数小于等于 2n2n。

这个方法的优点与上一份代码相同,同样可以减少很多需要处理的细节。

C++
#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 N = 100100;
int n;
char s[N], p[N];

void solve() {
	scanf("%d %s %s", &n, s, p);
	int c0 = 0, c1 = 0;
	for (int i = 0; i < n; i++) {
		if (s[i] == '0')
			c0++;
		else
			c1++;
		if (p[i] == '0')
			c0++;
		else
			c1++;
	}
	if (c0 <= n) {
		for (int i = 0; i < n; i++) {
			s[i] ^= 1;
			p[i] ^= 1;
		}
	}
	vector<int> ans1, ans2;
	for (int i = 0; i < n; i++) {
		if (s[i] == '1') {
			if (i > 0) ans1.push_back(i);
			ans1.push_back(i + 1);
		}
		if (p[i] == '1') {
			if (i > 0) ans2.push_back(i);
			ans2.push_back(i + 1);
		}
	}
	while(!ans2.empty()) {
		ans1.push_back(ans2.back());
		ans2.pop_back();
	}
	printf("%d", (int)ans1.size());
	for (int x : ans1)
		printf(" %d", x);
	printf("\n");
}

int main()
{
	startTime = clock();
//	freopen("input.txt", "r", stdin);
//	freopen("output.txt", "w", stdout);

	int t;
	scanf("%d", &t);
	while(t--) solve();

	return 0;
}

KAN

和第一份 Benq 的代码思路类似。

C++
#include <bits/stdc++.h>

using namespace std;

#ifdef LOCAL
    #define eprintf(...) fprintf(stderr, __VA_ARGS__)
#else
    #define eprintf(...) 42
#endif

using ll = long long;
using ld = long double;
using D = double;
using uint = unsigned int;
template<typename T>
using pair2 = pair<T, T>;
using pii = pair<int, int>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second

const int maxn = 100005;

char s[maxn];
int n;

vector<int> solve1()
{
	scanf("%s", s);
	s[n] = '0';
	vector<int> ans;
	for (int i = 0; i < n; i++) if (s[i] != s[i + 1]) ans.pb(i + 1);
	return ans;
}

void solve()
{
	scanf("%d", &n);
	auto ta = solve1();
	auto tb = solve1();
	while (!tb.empty())
	{
		ta.pb(tb.back());
		tb.pop_back();
	}
	printf("%d", (int)ta.size());
	for (auto t : ta) printf(" %d", t);
	printf("\n");
}

int main()
{
	int NT;
	scanf("%d", &NT);
	for (int T = 0; T < NT; T++)
	{
		solve();
	}
    return 0;
}

B. Unmerge

考虑将 aa 和 bb 合并后,来源相同的元素合并成一个子段,即 p=q1+q2+⋯+qkp = q_1 + q_2 + \cdots + q_k(qiq_i 是序列,“ ++ ” 是连接两个序列),发现一定满足,对于所有的 1≤i<k1\leq i < k,qiq_i 的所有元素都小于 qi+1q_{i+1} 的第一个元素。

考虑将 pp 划分成尽量多的,满足上述关系的子段 p=q1+q2+⋯+qkp = q_1 + q_2 + \cdots + q_k,发现符合条件的 aa 和 bb 一定是这些子段按顺序拼接得来的。

于是处理出上述每个子段的长度,跑 01 背包即可。

My Code

C++
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 2e3 + 5;
const int MAXM = MAXN * 2;

int p[MAXM];

void solve(void)
{
	int n;
	scanf("%d",&n);
	int m = n*2;
	for(int i=1; i<=m; ++i) scanf("%d",&p[i]);
	
	static vector<int> a;
	a.clear();
	for(int i=1,j=1; i<=m; i=j)
	{
		int mx = p[i];
		while(j<=m && mx>=p[j])
		{
			mx = max(mx, p[j]);
			++j;
		}
		a.push_back(j-i);
	}
	
	static bool f[MAXM][MAXN];
	
	for(int i=0; i<=m; ++i)
		for(int j=0; j<=n; ++j)
			f[i][j] = 0;
	
	f[0][0] = 1;
	for(int i=1; i<=(int)a.size(); ++i)
	{
		for(int j=0; j<=n; ++j)
		{
			f[i][j] = f[i-1][j];
			if(j >= a[i-1]) f[i][j] |= f[i-1][j - a[i-1]];
		}
	}
	if(f[(int)a.size()][n]) printf("Yes\n");
	else printf("No\n");
}

int main(void)
{
	int T;
	scanf("%d",&T);
	while(T--) solve();
	return 0;
}

Code

Benq

使用了 bitset 来加速 01 背包,写法更加简单。

C++
#include <bits/stdc++.h>
using namespace std;
 
typedef long long ll;
typedef long double ld;
typedef double db; 
typedef string str; 

typedef pair<int,int> pi;
typedef pair<ll,ll> pl; 
typedef pair<db,db> pd; 

typedef vector<int> vi; 
typedef vector<ll> vl; 
typedef vector<db> vd; 
typedef vector<str> vs; 
typedef vector<pi> vpi;
typedef vector<pl> vpl; 
typedef vector<pd> vpd; 

#define mp make_pair
#define f first
#define s second
#define sz(x) (int)(x).size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend() 
#define rsz resize
#define ins insert 
#define ft front() 
#define bk back()
#define pf push_front 
#define pb push_back
#define eb emplace_back 
#define lb lower_bound 
#define ub upper_bound 

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5; 
const ll INF = 1e18; 
const ld PI = acos((ld)-1);
const int xd[4] = {1,0,-1,0}, yd[4] = {0,1,0,-1}; 
mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count()); 

template<class T> bool ckmin(T& a, const T& b) { 
	return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) { 
	return a < b ? a = b, 1 : 0; } 
constexpr int pct(int x) { return __builtin_popcount(x); } 
constexpr int bits(int x) { return 31-__builtin_clz(x); } // floor(log2(x)) 
ll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } // divide a by b rounded up
ll fdiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // divide a by b rounded down
ll half(ll x) { return fdiv(x,2); }

template<class T, class U> T fstTrue(T lo, T hi, U f) {
	hi ++; assert(lo <= hi); // assuming f is increasing
	while (lo < hi) { // find first index such that f is true 
		T mid = half(lo+hi);
		f(mid) ? hi = mid : lo = mid+1; 
	} 
	return lo;
}
template<class T, class U> T lstTrue(T lo, T hi, U f) {
	lo --; assert(lo <= hi); // assuming f is decreasing
	while (lo < hi) { // find first index such that f is true 
		T mid = half(lo+hi+1);
		f(mid) ? lo = mid : hi = mid-1;
	} 
	return lo;
}
template<class T> void remDup(vector<T>& v) { 
	sort(all(v)); v.erase(unique(all(v)),end(v)); }

// INPUT
template<class A> void re(complex<A>& c);
template<class A, class B> void re(pair<A,B>& p);
template<class A> void re(vector<A>& v);
template<class A, size_t SZ> void re(array<A,SZ>& a);

template<class T> void re(T& x) { cin >> x; }
void re(db& d) { str t; re(t); d = stod(t); }
void re(ld& d) { str t; re(t); d = stold(t); }
template<class H, class... T> void re(H& h, T&... t) { re(h); re(t...); }

template<class A> void re(complex<A>& c) { A a,b; re(a,b); c = {a,b}; }
template<class A, class B> void re(pair<A,B>& p) { re(p.f,p.s); }
template<class A> void re(vector<A>& x) { trav(a,x) re(a); }
template<class A, size_t SZ> void re(array<A,SZ>& x) { trav(a,x) re(a); }

// TO_STRING
#define ts to_string
str ts(char c) { return str(1,c); }
str ts(const char* s) { return (str)s; }
str ts(str s) { return s; }
str ts(bool b) { 
	#ifdef LOCAL
		return b ? "true" : "false"; 
	#else 
		return ts((int)b);
	#endif
}
template<class A> str ts(complex<A> c) { 
	stringstream ss; ss << c; return ss.str(); }
str ts(vector<bool> v) {
	str res = "{"; F0R(i,sz(v)) res += char('0'+v[i]);
	res += "}"; return res; }
template<size_t SZ> str ts(bitset<SZ> b) {
	str res = ""; F0R(i,SZ) res += char('0'+b[i]);
	return res; }
template<class A, class B> str ts(pair<A,B> p);
template<class T> str ts(T v) { // containers with begin(), end()
	#ifdef LOCAL
		bool fst = 1; str res = "{";
		for (const auto& x: v) {
			if (!fst) res += ", ";
			fst = 0; res += ts(x);
		}
		res += "}"; return res;
	#else
		bool fst = 1; str res = "";
		for (const auto& x: v) {
			if (!fst) res += " ";
			fst = 0; res += ts(x);
		}
		return res;

	#endif
}
template<class A, class B> str ts(pair<A,B> p) {
	#ifdef LOCAL
		return "("+ts(p.f)+", "+ts(p.s)+")"; 
	#else
		return ts(p.f)+" "+ts(p.s);
	#endif
}

// OUTPUT
template<class A> void pr(A x) { cout << ts(x); }
template<class H, class... T> void pr(const H& h, const T&... t) { 
	pr(h); pr(t...); }
void ps() { pr("\n"); } // print w/ spaces
template<class H, class... T> void ps(const H& h, const T&... t) { 
	pr(h); if (sizeof...(t)) pr(" "); ps(t...); }

// DEBUG
void DBG() { cerr << "]" << endl; }
template<class H, class... T> void DBG(H h, T... t) {
	cerr << ts(h); if (sizeof...(t)) cerr << ", ";
	DBG(t...); }
#ifdef LOCAL // compile with -DLOCAL
	#define dbg(...) cerr << "LINE(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
#else
	#define dbg(...) 0
#endif

// FILE I/O
void setIn(str s) { freopen(s.c_str(),"r",stdin); }
void setOut(str s) { freopen(s.c_str(),"w",stdout); }
void unsyncIO() { ios_base::sync_with_stdio(0); cin.tie(0); }
void setIO(str s = "") {
	unsyncIO();
	// cin.exceptions(cin.failbit); 
	// throws exception when do smth illegal
	// ex. try to read letter into int
	if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
}

int n;

void solve() {
	re(n);
	vi p(2*n); re(p);
	vi sz;
	vi cur;
	trav(t,p) {
		if (sz(cur) && cur.ft > t) {
		} else {
			sz.pb(sz(cur));
			cur.clear();
		}
		cur.pb(t);
	}
	sz.pb(sz(cur));
	bitset<4001> res; res[0] = 1;
	trav(t,sz) res |= res<<t;
	if (res[n]) ps("YES");
	else ps("NO");
}

int main() {
	setIO();
	int T; re(T);
	F0R(i,T) solve();
	// you should actually read the stuff at the bottom
}

/* stuff you should look for
	* int overflow, array bounds
	* special cases (n=1?)
	* do smth instead of nothing and stay organized
	* WRITE STUFF DOWN
*/

Um_nik

也使用了 bitset。

C++
#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 N = 4020;
int n;
bitset<N> dp;

void solve() {
	scanf("%d", &n);
	for (int i = 0; i <= n; i++)
		dp[i] = 0;
	dp[0] = 1;
	int mx = 0;
	int x;
	int len = 0;
	for (int i = 0; i < 2 * n; i++) {
		scanf("%d", &x);
		if (x > mx) {
			dp |= dp << len;
			mx = x;
			len = 1;
		} else {
			len++;
		}
	}
	dp |= dp << len;
	if (dp[n])
		printf("YES\n");
	else
		printf("NO\n");
}

int main()
{
	startTime = clock();
//	freopen("input.txt", "r", stdin);
//	freopen("output.txt", "w", stdout);

	int t;
	scanf("%d", &t);
	while(t--) solve();

	return 0;
}s

C. Mastermind

贪心地考虑,先将出现次数最多的元素,进行完全的匹配(即,位置和颜色都相同),这样相当于减少了这些元素的出现次数。这一步可以用 priority_queue 实现。

对于 “ 颜色不相同 ” 的元素,因为颜色数为 n+1n+1,所以一定可以找到一个 bb 序列中没有出现的颜色。

考虑从剩下的 n−xn-x 个元素中选取 “ 颜色相同但位置不同 ” 的元素。考虑如果我们已经选取了这些元素,如何分配他们的位置,使得这些元素中没有颜色相同且位置相同的。假设选取的元素中,出现次数最多的一个出现了 pp 次,如果 p>(n−x)/2p > (n-x)/2,显然无法找到一个合法的分配方案。

我们排列一下剩余元素的下标,使得相同颜色的下标相邻,将这些颜色整体 “ 平移 ” ⌊(n−x)/2⌋\lfloor(n-x)/2\rfloor 位即可。然后,我们选取 n−yn-y 个位置,填入那个 bb 序列中没出现的颜色即可。注意要优先选择那些不合法的位置。如果填完之后还有不合法的位置,那么此题无解。

My Code

选取 y−xy-x 个 “ 颜色相同但位置不同 ” 的元素是此题的难点,一开始使用一种错误的策略写了很长时间。

C++
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<string>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 1e5 + 5;

int n,x,y;
int a[MAXN], ans[MAXN];

vector<int> clr[MAXN];

void solve_eq(void)
{
	static priority_queue<pii> q;
	while(!q.empty()) q.pop();
	
	for(int i=1; i<=n+1; ++i)
		q.push(make_pair((int)clr[i].size(), i));
	for(int i=1; i<=x; ++i)
	{
		pii now = q.top(); q.pop();
		int u = now.second;
		
		ans[clr[u].back()] = a[clr[u].back()];
		clr[u].pop_back();
		
		q.push(make_pair((int)clr[u].size(), u));
	}
}

void solve(void)
{
	scanf("%d%d%d",&n,&x,&y);
	for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
	
	for(int i=1; i<=n; ++i) ans[i] = 0;
	
	for(int i=1; i<=n+1; ++i) clr[i].clear();
	for(int i=1; i<=n; ++i)
		clr[a[i]].push_back(i);
	
	int non = 0;
	for(int i=1; i<=n+1; ++i)
		if(clr[i].empty()) non = i;
	
	solve_eq();
	
	static vector<int> rem;
	rem.clear();
	for(int i=1; i<=n+1; ++i)
		for(int j=0; j<(int)clr[i].size(); ++j)
			rem.push_back(clr[i][j]);
	
	rotate(rem.begin(), rem.begin() + (n-x)/2, rem.end());
	reverse(rem.begin(), rem.end());
	
	int cnt = 0;
	for(int i=1; i<=n+1; ++i)
		for(int j=0; j<(int)clr[i].size(); ++j)
		{
			int now = rem.back(); rem.pop_back();
			
			ans[now] = i;
			if(a[now] == i)
				++cnt, ans[now] = non;
		}
	
	if(cnt > n-y)
	{
		printf("No\n");
		return;
	}
	for(int i=1; i<=n+1 && cnt<n-y; ++i)
		if(ans[i] != non && ans[i] != a[i])
			++cnt, ans[i] = non;
	
	printf("Yes\n");
	for(int i=1; i<=n; ++i) printf("%d ",ans[i]);
	putchar('\n');
}

int main(void)
{
	int T;
	scanf("%d",&T);
	while(T--) solve();
	return 0;
}

Code

Benq

对于 ” 颜色相同位置不同 ” 的元素,统计剩余出现最多元素的出现次数 indind,i如果 n−x>2indn-x > 2ind,就选出 y−xy-x 个元素平移 indind 位;否则,选出一个出现次数最多的颜色,记录其出现的位置,再记录其他颜色出现的位置,交替放置即可。

代码中的 make 将记录答案的操作打了包,一定程度上减少了思考的细节。

C++
#include <bits/stdc++.h>
using namespace std;
 
typedef long long ll;
typedef long double ld;
typedef double db; 
typedef string str; 

typedef pair<int,int> pi;
typedef pair<ll,ll> pl; 
typedef pair<db,db> pd; 

typedef vector<int> vi; 
typedef vector<ll> vl; 
typedef vector<db> vd; 
typedef vector<str> vs; 
typedef vector<pi> vpi;
typedef vector<pl> vpl; 
typedef vector<pd> vpd; 

#define mp make_pair
#define f first
#define s second
#define sz(x) (int)(x).size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend() 
#define rsz resize
#define ins insert 
#define ft front() 
#define bk back()
#define pf push_front 
#define pb push_back
#define eb emplace_back 
#define lb lower_bound 
#define ub upper_bound 

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5; 
const ll INF = 1e18; 
const ld PI = acos((ld)-1);
const int xd[4] = {1,0,-1,0}, yd[4] = {0,1,0,-1}; 
mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count()); 

template<class T> bool ckmin(T& a, const T& b) { 
	return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) { 
	return a < b ? a = b, 1 : 0; } 
constexpr int pct(int x) { return __builtin_popcount(x); } 
constexpr int bits(int x) { return 31-__builtin_clz(x); } // floor(log2(x)) 
ll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } // divide a by b rounded up
ll fdiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // divide a by b rounded down
ll half(ll x) { return fdiv(x,2); }

template<class T, class U> T fstTrue(T lo, T hi, U f) {
	hi ++; assert(lo <= hi); // assuming f is increasing
	while (lo < hi) { // find first index such that f is true 
		T mid = half(lo+hi);
		f(mid) ? hi = mid : lo = mid+1; 
	} 
	return lo;
}
template<class T, class U> T lstTrue(T lo, T hi, U f) {
	lo --; assert(lo <= hi); // assuming f is decreasing
	while (lo < hi) { // find first index such that f is true 
		T mid = half(lo+hi+1);
		f(mid) ? lo = mid : hi = mid-1;
	} 
	return lo;
}
template<class T> void remDup(vector<T>& v) { 
	sort(all(v)); v.erase(unique(all(v)),end(v)); }

// INPUT
template<class A> void re(complex<A>& c);
template<class A, class B> void re(pair<A,B>& p);
template<class A> void re(vector<A>& v);
template<class A, size_t SZ> void re(array<A,SZ>& a);

template<class T> void re(T& x) { cin >> x; }
void re(db& d) { str t; re(t); d = stod(t); }
void re(ld& d) { str t; re(t); d = stold(t); }
template<class H, class... T> void re(H& h, T&... t) { re(h); re(t...); }

template<class A> void re(complex<A>& c) { A a,b; re(a,b); c = {a,b}; }
template<class A, class B> void re(pair<A,B>& p) { re(p.f,p.s); }
template<class A> void re(vector<A>& x) { trav(a,x) re(a); }
template<class A, size_t SZ> void re(array<A,SZ>& x) { trav(a,x) re(a); }

// TO_STRING
#define ts to_string
str ts(char c) { return str(1,c); }
str ts(const char* s) { return (str)s; }
str ts(str s) { return s; }
str ts(bool b) { 
	#ifdef LOCAL
		return b ? "true" : "false"; 
	#else 
		return ts((int)b);
	#endif
}
template<class A> str ts(complex<A> c) { 
	stringstream ss; ss << c; return ss.str(); }
str ts(vector<bool> v) {
	str res = "{"; F0R(i,sz(v)) res += char('0'+v[i]);
	res += "}"; return res; }
template<size_t SZ> str ts(bitset<SZ> b) {
	str res = ""; F0R(i,SZ) res += char('0'+b[i]);
	return res; }
template<class A, class B> str ts(pair<A,B> p);
template<class T> str ts(T v) { // containers with begin(), end()
	#ifdef LOCAL
		bool fst = 1; str res = "{";
		for (const auto& x: v) {
			if (!fst) res += ", ";
			fst = 0; res += ts(x);
		}
		res += "}"; return res;
	#else
		bool fst = 1; str res = "";
		for (const auto& x: v) {
			if (!fst) res += " ";
			fst = 0; res += ts(x);
		}
		return res;

	#endif
}
template<class A, class B> str ts(pair<A,B> p) {
	#ifdef LOCAL
		return "("+ts(p.f)+", "+ts(p.s)+")"; 
	#else
		return ts(p.f)+" "+ts(p.s);
	#endif
}

// OUTPUT
template<class A> void pr(A x) { cout << ts(x); }
template<class H, class... T> void pr(const H& h, const T&... t) { 
	pr(h); pr(t...); }
void ps() { pr("\n"); } // print w/ spaces
template<class H, class... T> void ps(const H& h, const T&... t) { 
	pr(h); if (sizeof...(t)) pr(" "); ps(t...); }

// DEBUG
void DBG() { cerr << "]" << endl; }
template<class H, class... T> void DBG(H h, T... t) {
	cerr << ts(h); if (sizeof...(t)) cerr << ", ";
	DBG(t...); }
#ifdef LOCAL // compile with -DLOCAL
	#define dbg(...) cerr << "LINE(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
#else
	#define dbg(...) 0
#endif

// FILE I/O
void setIn(str s) { freopen(s.c_str(),"r",stdin); }
void setOut(str s) { freopen(s.c_str(),"w",stdout); }
void unsyncIO() { ios_base::sync_with_stdio(0); cin.tie(0); }
void setIO(str s = "") {
	unsyncIO();
	// cin.exceptions(cin.failbit); 
	// throws exception when do smth illegal
	// ex. try to read letter into int
	if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
}

int n,x,y;
vi b, ans;
vi cnt[MX];
vi oc[MX];

void make(int a, int b) { // index, value
	assert(sz(cnt[a]));
	ans[cnt[a].bk] = b;
	cnt[a].pop_back();
}

void solve() {
	re(n,x,y); b.rsz(n); re(b); ans = vi(n);
	//dbg("OK",n,x,y,b);
	F0R(i,n+2) cnt[i].clear();
	F0R(i,n+1) oc[i].clear();
	F0R(i,n) cnt[b[i]].pb(i);
	int bad = 1; while (sz(cnt[bad])) bad ++;
	FOR(i,1,n+2) oc[sz(cnt[i])].pb(i);
	int ind = n;
	//dbg("STARTLOOP");
	//dbg("STARTLOOP");
	F0R(i,x) {
		while (!sz(oc[ind])) ind --;
		int z = oc[ind].bk; //dbg("CHOOSING",ind,z);
		oc[ind].pop_back(); make(z,z);
		oc[sz(cnt[z])].pb(z);
	}
	//dbg("MIDLOOP");
	while (!sz(oc[ind])) ind --;
	int BIG = oc[ind].bk;
	int lef = n-x, des = y-x, mx = min(2*(lef-ind),lef);
	//dbg(lef,des,mx);
	if (mx < des) {
		ps("NO");
		return;
	}
	if (mx == 2*(lef-ind)) {
		dbg("HUH");
		vi big, small;
		FOR(i,1,n+2) trav(t,cnt[i]) {
			if (i == BIG) big.pb(i);
			else small.pb(i);
		}
		assert(sz(big) >= sz(small));
		F0R(i,sz(small)) {
			if (des) des --, make(big[i],small[i]);
			if (des) des --, make(small[i],big[i]);
		}
		assert(des == 0);
	} else {
		dbg("NOPE");
		vi LEF;
		FOR(i,1,n+2) trav(t,cnt[i]) LEF.pb(i); // value, index
		assert(sz(LEF) == lef);
		F0R(i,des) make(LEF[i],LEF[(i+ind)%sz(LEF)]);
	}
	ps("YES");
	trav(t,ans) if (t == 0) t = bad;
	ps(ans);
	// fill up y-x
}

// choose x to match
// exactly y-x common, can't match
// can't get > max

int main() {
	setIO();
	int T; re(T);
	F0R(i,T) solve();
	// you should actually read the stuff at the bottom
}

/* stuff you should look for
	* int overflow, array bounds
	* special cases (n=1?)
	* do smth instead of nothing and stay organized
	* WRITE STUFF DOWN
*/

Um_nik

C++
#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 N = 100100;
int n, X, Y;
int a[N];
vector<int> forCol[N];

void solve() {
	scanf("%d%d%d", &n, &X, &Y);
	for (int i = 1; i <= n + 1; i++)
		forCol[i].clear();
	for (int i = 0; i < n; i++) {
		scanf("%d", &a[i]);
		forCol[a[i]].push_back(i);
	}
	if (X > Y) {
		printf("NO\n");
		return;
	}
	Y -= X;
	int bad = 1;
	while(!forCol[bad].empty()) bad++;
	for (int i = 0; i < n; i++)
		a[i] = bad;
	set<pii> setik;
	for (int i = 1; i <= n + 1; i++) {
		setik.insert(mp((int)forCol[i].size(), i));
	}
	while(X > 0) {
		int c = setik.rbegin()->second;
		setik.erase(mp((int)forCol[c].size(), c));
		a[forCol[c].back()] = c;
		forCol[c].pop_back();
		setik.insert(mp((int)forCol[c].size(), c));
		X--;
	}
	int mx = setik.rbegin()->second;
	vector<pii> cc;
	for (int j = 0; j < (int)forCol[mx].size(); j++)
		cc.push_back(mp(mx, forCol[mx][j]));
	for (int c = 1; c <= n + 1; c++) {
		if (c == mx) continue;
		for (int j = 0; j < (int)forCol[c].size(); j++)
			cc.push_back(mp(c, forCol[c][j]));
	}
	int z = (int)forCol[mx].size();
	if (2 * ((int)cc.size() - z) < Y) {
		printf("NO\n");
		return;
	}
	for (int i = 0; Y > 0 && i < (int)cc.size(); i++) {
		int p = (i + z) % (int)cc.size();
		if (cc[i].first != cc[p].first) {
			a[cc[i].second] = cc[p].first;
			Y--;
		}
	}
	assert(Y == 0);
	printf("YES\n");
	for (int i = 0; i < n; i++)
		printf("%d ", a[i]);
	printf("\n");
}

int main()
{
	startTime = clock();
//	freopen("input.txt", "r", stdin);
//	freopen("output.txt", "w", stdout);

	int t;
	scanf("%d", &t);
	while(t--) solve();

	return 0;
}

KAN

C++
#include <bits/stdc++.h>

using namespace std;

#ifdef LOCAL
    #define eprintf(...) fprintf(stderr, __VA_ARGS__)
#else
    #define eprintf(...) 42
#endif

using ll = long long;
using ld = long double;
using D = double;
using uint = unsigned int;
template<typename T>
using pair2 = pair<T, T>;
using pii = pair<int, int>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second

const int maxn = 100005;

vector<int> pos[maxn];
int n, bulls, cows;
priority_queue<pair2<int>> freq;
int a[maxn], b[maxn];
vector<pair2<int>> all;

void solve()
{
	scanf("%d%d%d", &n, &bulls, &cows);
	cows -= bulls;
	for (int i =0 ; i < n + 1; i++) pos[i].clear();
	for (int i =0 ; i < n; i++)
	{
		scanf("%d", &b[i]);
		b[i]--;
		pos[b[i]].pb(i);
	}
	for (int i = 0; i < n; i++) a[i] = -1;
	int missing_color = -1;
	while (!freq.empty()) freq.pop();
	for (int i = 0; i < n + 1; i++)
	{
		if (pos[i].empty()) missing_color = i;
		freq.push({(int)pos[i].size(), i});
	}
	assert(missing_color != -1);
	for (int i =0 ; i < bulls; i++)
	{
		int color = freq.top().se;
		freq.pop();
		a[pos[color].back()] = color;
		pos[color].pop_back();
		freq.push({(int)pos[color].size(), color});
	}
	all.clear();
	int max_occ = freq.top().fi;
	while (!freq.empty())
	{
		int color = freq.top().se;
		freq.pop();
		//cout << color << ' ' << (int)pos[color].size() << endl;
		for (auto t : pos[color]) all.pb({color, t});
	}
	//cout << "f " << (int)all.size() << ' ' << max_occ << endl;
	int max_cows = (int)all.size();
	if (2 * max_occ > (int)all.size()) max_cows -= 2 * max_occ - (int)all.size();
	if (cows > max_cows)
	{
		printf("NO\n");
		return;
	}
	int shift = (int)all.size() / 2;
	for (int i = 0; i < (int)all.size(); i++)
	{
		int j = (i + shift) % (int)all.size();
		int color = all[j].fi;
		if (all[i].fi == all[j].fi || cows == 0) color = missing_color;
		if (color != missing_color) cows--;
		a[all[i].se] = color;
	}
	printf("Yes\n");
	for (int i = 0; i < n; i++) printf("%d ", a[i] + 1);
	printf("\n");
}

int main()
{
	int NT;
	scanf("%d", &NT);
	for (int T = 0; T < NT; T++)
	{
		solve();
	}
    return 0;
}
原文
存档评论1 条抓取于