zoukankan      html  css  js  c++  java
  • 二进制数(dp,记忆化搜索)

    二进制数(dp,记忆化搜索)

    给定k个<=1e6的正整数x(k不大于10),问最小的,能被x整除且只由01组成的数。

    首先,dp很好写。用(f[i][j])表示i位01串,模ki的值是j的数是否存在。判断是否有(f[n][0])即可。然而dp的做法没有记忆化搜索快,原因是dp用到了一些冗余状态。如果p被访问过了,说明不用继续搜了。

    #include <cstdio>
    #include <string>
    #include <iostream>
    using namespace std;
    
    const int maxk=11, maxn=1e6+5;
    int k, n, a[maxk], vis[maxn];
    struct node{
        int x, len, pre, end; //x:当前数modKi  len:当前数的长度
        void set(int a, int b, int c, int d){
            x=a; len=b; pre=c; end=d; }
    }q[maxn*maxk];
    
    void bfs(int mod){
        int head=0, tail=0, t, ans; tail++;
        for (; head<tail; ++head){
            t=q[head].x*10%mod;
            if (!vis[t]){ vis[t]=1;
                q[tail++].set(t, q[head].len+1, head, 0);
            } if (t==0&&q[head].x){ ans=tail-1; break; }
            t=(q[head].x*10+1)%mod;
            if (!vis[t]){ vis[t]=1;
                q[tail++].set(t, q[head].len+1, head, 1);
            } if (t==0){ ans=tail-1; break; }
        }
        string s="";
        for (; ans; ans=q[ans].pre) s=char(q[ans].end+48)+s;
        cout<<"1"+s<<endl;
    }
    
    int main(){
        scanf("%d%d", &k, &n);
        for (int i=0; i<k; ++i){
            scanf("%d", &a[i]);
            if (a[i]==1){ puts("1"); continue; }
            for (int j=0; j<a[i]; ++j) vis[j]=0;
            q[0].set(1, 1, 0, 1); bfs(a[i]);
        }
        return 0;
    }
    
  • 相关阅读:
    openwrt 汉化
    错误: libstdc++.so.6: cannot open shared object file: No such file or directory
    openwrt uci
    openwrt makefile选项
    Ubuntu服务器断网问题解决
    lldpcli 常用命令
    openwrt ramips随记
    shell脚本学习(二)
    完成响应式的方式
    盒子模型 W3C中和IE中盒子的总宽度分别是什么
  • 原文地址:https://www.cnblogs.com/MyNameIsPc/p/8547367.html
Copyright © 2011-2022 走看看