2017 Latin American Regional Contests

E
记忆化搜索,水题。比赛时候没敢写,又觉得会超时(为什么要说又!),因为觉得暴搜接近10e1000,觉得就算是记忆化也优化不了。我依稀记得上次给学弟讲BFS里面也有个记忆化搜索也觉得会T没敢写(艹)。
从高位开始,利用大数取模的思路,vis【i】【j】记录 是否到达过该状态,并且此状态往后递归后有能不能找到答案。(i为第i位,j未前i位mod n后的余数,vis值为正数即来过,1为后面无解,2为后面有解)。递归结束时往前返回状态记录答案。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
int vis[1005][1005];
char ans[1005],s[1005];
int len,n;
int dfs(int loc,int lastremainder)
{
    if(loc>=len){
        return lastremainder==0?2:1;
    }
    if(vis[loc][lastremainder]){
        return vis[loc][lastremainder];
    }
    if(s[loc]=='?'){
        for(int i=!loc; i<=9; i++){
            if(dfs(loc+1,(lastremainder*10+i)%n)==2){
                ans[loc]+=i+'0';
                return  vis[loc][lastremainder]=2;
            }
        }
        return vis[loc][lastremainder]=1;
    }
    else{
        ans[loc]=s[loc];
        if(dfs(loc+1,(lastremainder*10+(s[loc]-'0'))%n)==2){
            return  vis[loc][lastremainder]=2;
        }
        return vis[loc][lastremainder]=1;
    }
}
int main(){
    cin>>s>>n;
    len=strlen(s);
    if(dfs(0,0)==2)
    cout<<ans<<endl;
    else
        puts("*");
}
/*
input
?294?? 17
output
129404
*/

猜你喜欢

转载自www.cnblogs.com/wkup/p/11814342.html