题解 P1074 【靶形数独】

题目link
本题最难的地方
Orz1
剩下的随便搜


#include<bits/stdc++.h>
using namespace std;
int a[10][10],vis[3][10][10],ans[10][10],bh[82],flag,maxn;
struct Row
{
    int h,zc;
}row[10];
int cmp(Row a,Row b)
{
    return a.zc<b.zc;
}
int Cast(int x,int y)
{
    if(x>=1&&x<=3)
	{
        if(y>=1&&y<=3)
        {
        	return 1;
        }
        else
        {
        	if(y>=4&&y<=6)
        	{
        		return 2;
        	}
			else
        	{
        		return 3;
        	}
        }
    }
    if(x>=4&&x<=6)
	{
        if(y>=1&&y<=3)
        {
        	return 4;
        }
        else
        {
        	if(y>=4&&y<=6)
        	{
        		return 5;
			} 
			else
        	{
        		return 6;
        	}
        }
        
    }
    if(x>=7&&x<=9)
	{
        if(y>=1&&y<=3)
        {
        	return 7;
		} 
        else
        {
        	if(y>=4&&y<=6)
        	{
        		return 8;
			} 
        	else
        	{
        		return 9;
			}
		} 
    }
}
int Score(int x,int y)
{
    if(x==1||y==1||x==9||y==9)
    {
    	return 6;
	}	
    else
    {
    	if(x==2||y==2||x==8||y==8)
    	{
    		return 7;
		} 	
    	else
    	{
    		if(x==3||y==3||x==7||y==7)
    		{
    			return 8;
			} 
    		else
    		{
    			if(x==4||y==4||x==6||y==6)
    			{
    				return 9;
				} 
				else
				{
					return 10;
				} 
			} 
		} 
	} 
}
int calc()
{
    int sum=0;
    for(int i=1;i<=9;i++)
    {
    	for(int j=1;j<=9;j++)
    	{
    		sum+=ans[i][j]*Score(i,j);
		} 
	} 
    return sum;
}
void dfs(int xh)
{
    if(xh==82)
	{
        flag=1;
        maxn=max(maxn,calc());
        return ;
    }
    int x=bh[xh]/9+1;
    int y=bh[xh]%9;
    if(y==0)
    {
    	x=bh[xh]/9;
		y=9;
	} 
    if(!a[x][y])
	{
        for(int j=1;j<=9;j++)
		{
            int g=Cast(x,y);
            if(!vis[0][x][j]&&!vis[1][y][j]&&!vis[2][g][j])
			{
                ans[x][y]=j;
                vis[0][x][j]=1;
				vis[1][y][j]=1;
				vis[2][g][j]=1;
                dfs(xh+1);
                vis[0][x][j]=0;
				vis[1][y][j]=0;
				vis[2][g][j]=0;
            }
        }
    }
    else
    {
    	dfs(xh+1);
	} 
}
int main()
{
	for(int i=1;i<=9;i++)
	{
        for(int j=1;j<=9;j++)
		{
            cin>>a[i][j];
            if(a[i][j]==0)
            {
            	row[i].zc++;
            }
            else
			{
                int v=a[i][j];
                int g=Cast(i,j);
                ans[i][j]=v;
                vis[0][i][v]=1;
				vis[1][j][v]=1;
				vis[2][g][v]=1;
            }
        }
        row[i].h=i;
    }
    sort(row+1,row+1+9,cmp);
    int num=0;
    for(int i=1;i<=9;i++)
	{
        for(int j=1;j<=9;j++)
		{
            int x=row[i].h,y=j;
            num++;
            bh[num]=(x-1)*9+y;
        }
    }
    dfs(1);
    if(flag)
    {
    	cout<<maxn<<endl;
    }
    else
    {
    	cout<<-1<<endl;
    }
} 
posted @ 2019-05-09 21:58  G_A_TS  阅读(460)  评论(0编辑  收藏  举报