0x20「搜索」

版权声明:本文为博主原创文章,未经博主允许不得转载,欢迎前往zory.cf获得最佳体验 https://blog.csdn.net/Zory_Programmer/article/details/80981952

今天没带u盘,用blog存着,明天会放到zory.cf上面的

2201 小猫爬山

这道题引发了我对暴搜方式的思考:
如果用车来找猫,就有次序性;
而反过来,新车选择就会减少,次序也固定

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int MAXN=20;

int n,w;
int ans=MAXN;
int use[MAXN];
int c[MAXN];
void dfs(int now,int cnt)
{
    if(cnt>=ans) return;//最优化剪枝 
    if(now>n) {ans=cnt;return;}

    for(int i=1;i<=cnt;i++)
        if(use[i]+c[now]<=w)
        {
            use[i]+=c[now];
            dfs(now+1,cnt);
            use[i]-=c[now];
        }
    use[cnt+1]=c[now];
    dfs(now+1,cnt+1);
}

bool cmp(int x,int y) {return x>y;}
int main()
{
    scanf("%d%d",&n,&w);
    for(int i=1;i<=n;i++) scanf("%d",&c[i]);
    sort(c+1,c+n+1,cmp);//减少选择 
    dfs(1,0);
    printf("%d",ans);
}

poj2676 poj3074 Sudoku

poj2676 0ms
poj3074 tle,精A

#include<cstdio>
#include<cstring>
#include<cmath>
#include<bitset>
#include<algorithm>
using namespace std;
const int MAXN=20;
const int INF=0x3f3f3f3f;

int mp[MAXN][MAXN];
bitset<10> hang[MAXN],lie[MAXN],block[MAXN];
int getid(int x,int y) { return ((x-1)/3)*3+(y-1)/3+1; }

int tot;
int fx,fy;
void getnxt()
{
    int ans=INF;
    for(int i=1;i<=9;i++)
        for(int j=1;j<=9;j++)
            if(mp[i][j]==0)
            {
                int t=(hang[i]&lie[j]&block[getid(i,j)]).count();
                if(ans>t) ans=t,fx=i,fy=j;
            }
}

bool bk;
void dfs(int now)
{
    if(bk) return;
    if(now>tot)
    {
        for(int i=1;i<=9;i++)
        {
            for(int j=1;j<=9;j++)
                printf("%d",mp[i][j]);
            putchar('\n');
        }
        //putchar('\n');

        bk=1;
        return;
    }

    getnxt();//debug 原本直接用fx、fy,后果严重,查错很久! 
    int x=fx,y=fy,id=getid(x,y);
    for(int t=1;t<=9;t++)
        if(hang[x][t] and lie[y][t] and block[id][t])
        {
            hang[x][t]=lie[y][t]=block[id][t]=0;
            mp[x][y]=t;
            dfs(now+1);
            mp[x][y]=0;
            hang[x][t]=lie[y][t]=block[id][t]=1;
        }
}

char str[MAXN*MAXN];
int main()
{
    int T;scanf("%d",&T);
    while(T--)
    //while(1)
    {
        tot=0;
        for(int i=1;i<=9;i++) hang[i].set(),lie[i].set(),block[i].set();

        //scanf("%s",str+1);
        if(str[1]=='e') break;

        for(int i=1;i<=9;i++)
        {
            scanf("%s",str+1);
            for(int j=1;j<=9;j++)
            {
                int now=str[j]-'0';
                //int now=(str[(i-1)*9+j]=='.')?0:str[(i-1)*9+j]-'0';
                mp[i][j]=now;

                if(now>0) hang[i][now]=lie[j][now]=block[getid(i,j)][now]=0;
                else tot++;
            }
        }

        bk=0;dfs(1);
    }
}

猜你喜欢

转载自blog.csdn.net/Zory_Programmer/article/details/80981952