CF2228C2
_tzhengqing_ · · 题解
题目传送门
难度:上位黄/下位绿
考虑从高位往低位枚举数字,设枚举到第
复杂度分析:由于只有与
细节:当
#include <iostream>
#include <algorithm>
#define int long long
using namespace std;
int n,m,k,l,ans,T,len,a[2005],b[2005];
void dfs(int x,int up,int step)
{
if(x || !a[1])ans = min(ans,abs(x - m));
if(!up)
{
int w = x;
while(x <= 1e17)x = x * 10 + a[n],ans = min(ans,abs(x - m));
x = w;
while(x <= 1e17)x = x * 10 + a[1],ans = min(ans,abs(x - m));
return ;
}
if(x > 1e17)return ;
for(int i = 1;i <= n;i ++)
{
if(x == 0 && !a[i])continue ;
if(a[i] == b[len - step + 1])dfs(x * 10 + a[i],1,step + 1);
else dfs(x * 10 + a[i],0,step + 1);
}
}
void solve()
{
cin >> m >> n;
ans = 1e18;
for(int i = 1;i <= n;i ++)cin >> a[i];
len = 0;int p = m;
while(p)b[++len] = p % 10,p /= 10;
dfs(0,1,1);
cout << ans << '\n';
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin >> T;
while(T --)solve();
}