hdu2718双重dfs+剪枝

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. 

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
题目大意,给你递增的一位数,不重复,全部用上组合成两个数,使差最小,方法很多,我用的是搜索穷举,首先判定两个数位数一定是相等或相差1,然后枚举第一个数和第二个数,思路简单,代码如下:

#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;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值