Codeforces GYM 100646E: Su-Su-Sudoku 题解

本文详细解析了Codeforces GYM中编号为100646E的Su-Su-Sudoku问题,重点介绍了如何利用基础搜索策略配合位运算优化判重过程,同时强调了在验证输入时排除重复的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

非常基础的搜索题

用位运算可以加速判重的过程

别忘了判断输入的部分是否有重复

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <utility>
#include <map>
#include <stack>
#include <set>
#include <vector>
#include <queue>
#include <deque>
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define LL long long
#define Pair pair<int,int>
#define LOWBIT(x) x & (-x)
using namespace std;

const int INF=0x7ffffff;
inline int getk(int x,int y)
{
	int dr,dc;
	dr=(x+2)/3;dc=(y+2)/3;
	return (dr-1)*3+dc;
}

int rused[15],cused[15],kused[15];
vector<Pair> v;
int a[15][15];

bool dfs(int step)
{
	if (step==6) return true;
	int xx=v[step-1].x,yy=v[step-1].y;
	int used=rused[xx]|cused[yy]|kused[getk(xx,yy)];
	for (int i=1;i<=9;i++)
	{
		if (used&(1<<(i-1))) continue;
		a[xx][yy]=i;
		rused[xx]^=(1<<(i-1));
		cused[yy]^=(1<<(i-1));
		kused[getk(xx,yy)]^=(1<<(i-1));
		if (dfs(step+1)) return true;
		a[xx][yy]=0;
		rused[xx]^=(1<<(i-1));
		cused[yy]^=(1<<(i-1));
		kused[getk(xx,yy)]^=(1<<(i-1));
	}
	return false;
}
int main ()
{
	bool ff;
	int t,i,j,x;
	scanf("%d",&t);
	string s;
	while (t--)
	{
		v.clear();
		memset(rused,0,sizeof(rused));
		memset(cused,0,sizeof(cused));
		memset(kused,0,sizeof(kused));
		ff=true;
		for (i=1;i<=9;i++)
		{
			cin>>s;
			for (j=1;j<=9;j++)
			{
				a[i][j]=s[j-1]-'0';
				//scanf("%d",&a[i][j]);
				x=a[i][j];
				if (x!=0)
				{
					if (rused[i]&(1<<(x-1)))
					{
						ff=false;
						break;
					}
					rused[i]|=(1<<(x-1));
					if (cused[j]&(1<<(x-1)))
					{
						ff=false;
						break;
					}
					cused[j]|=(1<<(x-1));
					if (kused[getk(i,j)]&(1<<(x-1)))
					{
						ff=false;
						break;
					}
					kused[getk(i,j)]|=(1<<(x-1));
				}
				else
					v.pb(mp(i,j));
			}
			//if (!ff) break;
		}
		if (!ff)
		{
			printf("Could not complete this grid.\n\n");
			continue;
		}
		if (dfs(1))
		{
			for (i=1;i<=9;i++)
			{
				for (j=1;j<=9;j++)
					printf("%d",a[i][j]);
				printf("\n");
			}
			printf("\n");
		}
		else
			printf("Could not complete this grid.\n\n");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值