萌新刚学dfs
查看原帖
萌新刚学dfs
107232
twelveZ楼主2020/7/10 21:51

如题,评测记录

#pragma GCC optimize("O3,Ofast,inline,unroll-all-loops,-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,popcnt")
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
int n;
char s1[28], s2[28], s3[28], s4[28];
char q[28];
char endans[19260817][3];
char ans[19260817][3];
int anslen;
int t1, t2, t3, t4;
void print() {
	for (int i = 1; i <= anslen; i++) {
		for (int j = 0; j <= 2; j++)
			printf("%c ", endans[i][j]);
		putchar('\n');
	}
}
bool check(int len) {
	if (len < anslen) return 1;
	for (int i = 1; i <= len; i++) {
		for (int j = 0; j <= 2; j++) {
			if (ans[i][j] < endans[i][j])return 1;
			if (ans[i][j] > endans[i][j]) return 0;
		}
	}
	return 0;
}
void cop(int len) {
	for (int i = 1; i <= len; i++) {
		for (int j = 0; j <= 2; j++) {
			endans[i][j] = ans[i][j];
		}
	}
	anslen = len;
}
void DEBUG () {
	printf("A:");
	for (int i = 1; i <= t1; i ++) {
		printf("%c", s1[i]);
	}
	printf("\nB:");
	for (int i = 1; i <= t2; i ++) {
		printf("%c", s2[i]);
	}
	printf("\nC:");
	for (int i = 1; i <= t3; i ++) {
		printf("%c", s3[i]);
	}
	printf("\nD:");
	for (int i = 1; i <= t4; i ++) {
		printf("%c", s4[i]);
	}
	puts("");
//	puts("");
}
bool cut () {
	for (int i = 1; i <= t4; i ++) {
		if (s4[i] != q[i]) return 0;
	}
	return 1;
}
void search(int opt) {
	if (s4[t4] != q[t4] || opt + n - t4 > anslen) return ;
	if (t4 == n && strcmp(s4 + 1, q + 1) == 0) {
		if (check(opt - 1))
			cop(opt - 1);
		return;
	}
	char top;
	if (t1 > 0) {
		ans[opt][1] = 'A';
		ans[opt][2] = 'B';
		top = s1[t1--];
		ans[opt][0] = top;
		s2[++t2] = top;
		search(opt + 1);
		s1[++t1] = top;
		t2--;
	}
	if (t1 > 0) {
		ans[opt][1] = 'A';
		ans[opt][2] = 'C';
		top = s1[t1--];
		ans[opt][0] = top;
		s3[++t3] = top;
		search(opt + 1);
		s1[++t1] = top;
		t3--;
	}
	if (t1 > 0) {
		ans[opt][1] = 'A';
		ans[opt][2] = 'D';
		top = s1[t1--];
		ans[opt][0] = top;
		s4[++t4] = top;
		search(opt + 1);
		s1[++t1] = top;
		t4--;
	}
	if (t2 > 0) {
		ans[opt][1] = 'B';
		ans[opt][2] = 'C';
		top = s2[t2--];
		ans[opt][0] = top;
		s3[++t3] = top;
		search(opt + 1);
		s2[++t2] = top;
		t3--;
	}
	if (t2 > 0) {
		ans[opt][1] = 'B';
		ans[opt][2] = 'D';
		top = s2[t2--];
		ans[opt][0] = top;
		s4[++t4] = top;
		search(opt + 1);
		s2[++t2] = top;
		t4--;
	}
	if (t3 > 0) {
		ans[opt][1] = 'C';
		ans[opt][2] = 'D';
		top = s3[t3--];
		ans[opt][0] = top;
		s4[++t4] = top;
		search(opt + 1);
		s3[++t3] = top;
		t4--;
	}

}
int main() {
	scanf("%d%s", &n, q + 1);
	reverse (q + 1, q + n + 1);
	for (int i = 1; i <= n; i++) {
		s1[i] = i + 'a' - 1;
	}
	t1 = n;
	anslen = 2147483647;
	search(1);
	if (anslen != 2147483647) 
		print();
	else
	puts("NO");
}

求剪枝方案

禁止无意义回复

2020/7/10 21:51
加载中...