Given a number of distinct decimal digits, you can form one integer by choosing a non-empty subset of these digits and writing them in some order. The remaining digits can be written down in some order to form a second integer. Unless the resulting integer is 0, the integer may not start with the digit 0.
题目大意,给你递增的一位数,不重复,全部用上组合成两个数,使差最小,方法很多,我用的是搜索穷举,首先判定两个数位数一定是相等或相差1,然后枚举第一个数和第二个数,思路简单,代码如下:
For example, if you are given the digits 0, 1, 2, 4, 6 and 7, you can write the pair of integers 10 and 2467. Of course, there are many ways to form such pairs of integers: 210 and 764, 204 and 176, etc. The absolute value of the difference between the integers in the last pair is 28, and it turns out that no other pair formed by the rules above can achieve a smaller difference.
input
1
0 1 2 4 6 7
output
28
#include<iostream>
#include<cstring>
#include<string>
#include<vector>
#include<cmath>
using namespace std;
int isv1[10];
int isv2[10];
int inf=1<<29;
int l1,l2,val1,ans=inf;
vector<int> v;
int deci[10]={1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000};
void dfs2(int deep,int val){
int t=abs(val*deci[l2-deep]-val1);
if (deep!=0&&t >ans) return;//剪枝,如果当前数后面补零之后已经与val1差大于ans,则返回;
if (deep==l2){
ans=ans>t?t:ans;
return;
}
for (int i=0;i<v.size();i++){
if (deep==0&&v[i]==0) continue;
if (!isv1[v[i]]&&!isv2[v[i]]){
isv2[v[i]]=1;
dfs2(deep+1,val*10+v[i]);
isv2[v[i]]=0;
}
}
}
void dfs1(int deep,int val){
if (deep==l1){
val1=val;
memset(isv2,0,sizeof(isv2));
dfs2(0,0);
return;
}
for (int i=0;i<v.size();i++){
if (!isv1[v[i]]){
if (v[i]==0&&deep==0) continue;
isv1[v[i]]=1;
dfs1(deep+1,val*10+v[i]);
isv1[v[i]]=0;
}
}
}
int main(){
int T;
cin>>T;
string s;
getchar();
while(T--){
v.clear();
getline(cin,s);
ans=inf;
for (int i=0;i<s.length();i++){
if (s[i]>='0'&&s[i]<='9')
{
v.push_back(s[i]-'0');
}
}
l1=v.size()/2;
l2=v.size()-l1;
dfs1(0,0);
if (ans==inf) cout<<v[1]<<endl;
else cout<<ans<<endl;
}
}