Nastya and Scoreboard

分析:

(dfs) 剪枝+贪心。
如果用记忆化搜索,应该可以保证时间复杂度更优。
传送门

代码:

#include <bits/stdc++.h>
using namespace std;
const int N=2020;
int num[10]={119,18,93,91,58,107,111,82,127,123};
int p[N],ans[N],n;
bool vis[N][N],f;
void dfs(int v,int t)
{
    if(vis[v][t])//如果还会遇到这种情况,说明之前这种情况肯定不可行,剪枝
        return;
    vis[v][t]=1;
    if(v==n+1)
    {
        if(t==0)
            f=1;
        return;
    }
    for(int i=9;i>=0;i--)
    {
        int x=__builtin_popcount(num[i]^p[v]);
        if((num[i]|p[v])==num[i]&&x<=t)
        {
            ans[v]=i;
            dfs(v+1,t-x);
        }
        if(f) return;
    }
}
int main()
{
    int k;
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)
    {
        char s[10]={};
        scanf("%s",s);
        int a=0;
        for(int j=0;j<7;j++)
            a=(a<<1)+(s[j]-'0');
        p[i]=a;
    }
    f=0;
    dfs(1,k);
    if(f)
    {
        for(int i=1;i<=n;i++)
            printf("%d",ans[i]);
        printf("
");
    }
    else
        printf("-1
");
    return 0;
}
/*
https://www.cnblogs.com/charles1999/p/12766333.html
*/

原文地址:https://www.cnblogs.com/1024-xzx/p/12786697.html