社区讨论

too short on line 1 是什么意思?不理解,输出感觉都是正确的

P1406方格填数参与者 3已保存回复 2

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
2 条
当前快照
1 份
快照标识符
@lo2tv5t3
此快照首次捕获于
2023/10/23 19:41
2 年前
此快照最后确认于
2023/10/23 19:41
2 年前
查看原帖
CPP
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int n, a[20], st[20], ans[5][5], sum;

void Print() {
	for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (j == n) cout << ans[i][j] << endl;
			else cout << ans[i][j] << " ";
}

bool check(int r, int c, int idx) {
	if (c == n) {
		int res = a[idx];
		for (int i = 1 ; i < n ; ++i) {
			res += ans[r][i];
		}
		if (res != sum) return true;
	}
	if (r == n) {
		int res = a[idx];
		for (int i = 1 ; i < n ; ++i) {
			res += ans[i][c];
		}
		if (res != sum) return true;
	}
	if (r == n && c == n) {
		int res = a[idx];
		for (int i = 1 ; i < n ; ++i) {
			res += ans[i][i];
		}
		if (res != sum) return true;
	}
	if (r == n && c == 1) {
		int res = a[idx];
		for (int i = 1 ; i < n ; ++i) {
			res += ans[i][n - i + 1];
		}
		if (res != sum) return true;
	}
	return false;
}

void dfs(int r, int c) {
	if (r == n + 1) {
		Print();
		exit(0);
	}
	for (int i = 1 ; i <= n * n; ++i) {
		if (!st[i]) {
			if (check(r, c, i)) continue;
			st[i] = 1;
			ans[r][c] = i;
			if (c == n) dfs(r + 1, 1);
			else dfs(r, c + 1);
			st[i] = 0;
		}
	}
}

int main() {
	cin >> n;
	for (int i = 1 ; i <= n * n; ++i) {
		cin >> a[i];
		sum += a[i];
	}

	sum = sum / n;
	cout << sum << endl;
	
	sort(a + 1, a + n + 1);
	dfs(1, 1);

	return 0;
}

回复

2 条回复,欢迎继续交流。

正在加载回复...