二分图染色40pts元素反应求调玄关
查看原帖
二分图染色40pts元素反应求调玄关
1284582
F_L_Bird楼主2025/1/29 14:32

record

#include<iostream>
#include<stack>
#include<vector>
using namespace std;

int n,a[1005],f[1005],col[1005],cnt1,cnt2,ans1,ans2,main_col,now = 1;

vector<int> e[1005];
stack<int> stk1,stk2;

bool dfs(int u,int c) {		//二分图染色
	col[u] = c;
	if(c == 1) {
		cnt1 += 1;
	} else {
		cnt2 += 1;
	}
	bool res = true;
	for(int i = 0; i < int(e[u].size()); i += 1) {
		int v = e[u][i];
		if(col[v] == 0) {
			res &= dfs(v,3 - c);
		} else if(col[v] == c) {
			return false;
		}
	}
	return res;
}

void refill(int u) {		//颜色反转
	col[u] = 3 - col[u];
	for(int i = 0; i < int(e[u].size()); i += 1) {
		int v = e[u][i];
		if(col[v] == col[u]) {
			refill(v);
		}
	}
	return;
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin>>n;
	for(int i = 1; i <= n; i += 1) {
		cin>>a[i];
	}
	f[n] = a[n];
	for(int i = n - 1; i >= 1; i -= 1) {
		f[i] = min(a[i],f[i + 1]);
	}
	for(int i = 1; i <= n - 2; i += 1) {		//二分图建图
		for(int j = i + 1; j <= n - 1; j += 1) {
			if(f[j + 1] < a[i] && a[i] < a[j]) {
				e[i].push_back(j);
				e[j].push_back(i);
			}
		}
	}
	for(int i = 1; i <= n; i += 1) {		//二分图染色
		cnt1 = 0;
		cnt2 = 0;
		if(col[i] == 0 && !dfs(i,1)) {
			cout<<0;
			return 0;
		} else {
			ans1 += max(cnt1,cnt2);
			ans2 += min(cnt1,cnt2);
			if(cnt1 < cnt2) {
				refill(i);
			}
		}
	}
	for(int i = 1; i <= n; i += 1) {		//排序
		if(col[i] == 1) {
			while(!stk1.empty() && stk1.top() == now) {
				stk1.pop();
				cout<<"b ";
				now += 1;
			}
			stk1.push(a[i]);
			cout<<"a ";
		} else {
			while((!stk1.empty() && stk1.top() == now) || (!stk2.empty() && stk2.top() == now)) {
				if(!stk1.empty() && stk1.top() == now) {
					stk1.pop();
					cout<<"b ";
				} else {
					stk2.pop();
					cout<<"d ";
				}
				now += 1;
			}
			stk2.push(a[i]);
			cout<<"c ";
		}
	}
	while(now <= n) {	//清空栈内剩余元素
		if(!stk1.empty() && stk1.top() == now) {
			stk1.pop();
			cout<<"b ";
		} else {
			stk2.pop();
			cout<<"d ";
		}
		now += 1;
	}
	return 0;
}
2025/1/29 14:32
加载中...