20分,WA求助(WA on #1#3#4#5)
查看原帖
20分,WA求助(WA on #1#3#4#5)
770891
NTT__int128楼主2024/3/18 22:24
#include <bits/stdc++.h>
using namespace std ;
int n , a[20] , p[5][5] , cnt ;
bitset <20> v ;
void work()
{
	for(int i = 1 ; i <= n ; i++)	v[p[n][i]] = 0 ;
}
void work2()
{
	for(int i = 1 ; i <= n ; i++)	p[n][i] = 0 ;
}
void dfs(int t)
{
	if(t > (n - 1) * n)
	{
		for(int i = 1 ; i <= n ; i++)
		{
			int tmp = 0 ;
			for(int j = 1 ; j < n ; j++)	tmp += p[j][i] ;
			int now = cnt - tmp ;
			int pos = lower_bound(a + 1 , a + n * n + 1 , now) - a ;
			while(v[pos] && a[pos + 1] == a[pos])	pos++ ;
			if(a[pos] != now || v[pos])
			{
				work() ;
				work2() ;
				return ;
			}
			v[pos] = 1 ;
			p[n][i] = now ;
		}
		int tmp = 0 ;
		for(int i = 1 ; i <= n ; i++)	tmp += p[i][i] ;
		if(tmp != cnt)
		{
			work() ;
			work2() ;
			return ;
		}
		tmp = 0 ;
		for(int i = 1 ; i <= n ; i++)	tmp += p[i][n - i + 1] ;
		if(tmp != cnt)
		{
			work() ;
			work2() ;
			return ;
		}
		for(int i = 1 ; i <= n ; i++)
		{
			for(int j = 1 ; j <= n ; j++)	cout << p[i][j] << ' ' ;
			cout << '\n' ;
		}
		exit(0) ;
	}
	int x = t / n + 1 , y = t % n ;
	if(t % n == 0)	x-- , y = n ;
	if(y == n)
	{
		int tmp = 0 ;
		for(int i = 1 ; i < n ; i++)	tmp += p[x][i] ;
		int now = cnt - tmp ;
		int pos = lower_bound(a + 1 , a + n * n + 1 , now) - a ;
		if(a[pos] != now || v[pos])	return ;
		v[pos] = 1 ;
		p[x][n] = now ;
		dfs(t + 1) ;
		v[pos] = 0 ;
		p[x][n] = 0 ;
	}
	else
	{
		for(int i = 1 ; i <= n * n ; i++)
		{
			if(!v[i])
			{
				v[i] = 1 ;
				p[x][y] = a[i] ;
				dfs(t + 1) ;
				v[i] = 0 ;
				p[x][y] = 0 ;
			}
		}
	}
}
bool cmp(int x , int y)
{
	return x < y ;
}
int main()
{
	cin >> n ;
	for(int i = 1 ; i <= n * n ; i++)	cin >> a[i], cnt += a[i] ;
	sort(a + 1 , a + n * n + 1 , cmp) ;
	cnt /= n ;
	cout << cnt << '\n' ;
	if(n == 1)
	{
		cout << a[1] ;
		return 0 ;
	}
	dfs(1) ;
	return 0 ;
}
2024/3/18 22:24
加载中...