怎么按字典序输出答案啊?求大佬指导
查看原帖
怎么按字典序输出答案啊?求大佬指导
630082
Enzoy楼主2022/10/26 16:07
#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<vector>
#include<list>
#include<map>
#include<queue>
#include<stack>
#include<bitset>

using namespace std;

typedef long long ll;
#define starburst ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define pb push_back

const int N = 20;
int n;
int ans[N];
bool row[N], col[N], dg[N * 2], udg[N * 2];
int sum = 0;

void dfs(int x,int y,int s)
{
	if (s > n) return;
	if (y == n)
	{
		y = 0;
		x++;
		return;
	}
	if (x == n)
		if (s == n)
		{
			sum++;
			if (sum <= 3) 
			{
				for (int i = 1; i <= n; i++)
					cout << ans[i] << " ";
				puts("");
			}
			
			return;
		}

	dfs(x, y + 1, s);

	if (!row[x] && !col[y] && !dg[x + y] && !udg[n - y + x])
	{
		row[x] = col[y] = dg[x + y] = udg[n - y + x] = true;
		ans[x] = y + 1;
		dfs(x + 1, 0, s + 1);
		row[x] = col[y] = dg[x + y] = udg[n - y + x] = false;

	}

}

int main()
{
	cin>>n;
	
	dfs(0, 0, 0);

	cout << sum << endl; 
	return 0;
}

2022/10/26 16:07
加载中...