Smallest Difference POJ - 2718(全排列)

给定若干位十进制数,你可以通过选择一个非空子集并以某种顺序构建一个数。剩余元素可以用相同规则构建第二个数。除非构造的数恰好为0,否则不能以0打头。

举例来说,给定数字0,1,2,4,6与7,你可以写出10和2467。当然写法多样:210和764,204和176,等等。最后一对数差的绝对值为28,实际上没有其他对拥有更小的差。

Input - 输入

输入第一行的数表示随后测试用例的数量。
对于每组测试用例,有一行至少两个不超过10的十进制数字。(十进制数字为0,1,…,9)每行输入中均无重复的数字。数字为升序给出,相隔恰好一个空格。

Output - 输出

对于每组测试用例,输出一个以上述规则可获得的最小的差的绝对值在一行。

Sample Input - 输入样例

1
0 1 2 4 6 7

Sample Output - 输出样例

28

这道题目是个全排列搜索最优答案的题目,我们借助全排列函数(毕竟数据量不大)来完成搜索到所有的情况,然后从中截取两个数出来,穷尽搜索,但是也是有限制条件的,两个数字的首位不能是0.

代码:


#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<queue>
#include<algorithm>
const int maxn=5005;
typedef long long ll;
using namespace std;
typedef pair<ll,ll> p;
#include<string>
int a[maxn];

int permutation(int *b,int n)
{
	int inf=99999999;
	int i;

	do
	{
		if(b[0]==0)
			continue;
		int mid=(n+1)/2;
		int c=0,d=0;
		if(b[mid])
		{	
			for(i=0;i<mid;i++)
			{
				c=c*10+a[i];
			}

			for(i=mid;i<n;i++)
			{
				d=d*10+a[i];
			}
			inf=min(inf,abs(c-d));
		}

	}while(next_permutation(b,b+n));


	return inf;
}


int main()
{
	int i;
	int n;
	cin>>n;
	getchar();
	while(n--)
	{
		int k=0;
		string s;
		getline(cin,s);
		for(i=0;i<s.length();i++)
			if(s[i]>='0'&&s[i]<='9')
				a[k++]=s[i]-'0';
		if(k==2)
		{
			cout<<a[1]-a[0]<<endl;
			continue;
		}	

		cout<<permutation(a,k)<<endl;
	}
	return 0;
}



 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值