您的位置:首页 > Web前端

poj 2718 Smallest Difference

2018-03-13 17:16 483 查看
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.InputThe first line of input contains the number of cases to follow. For each case, there is one line of input containing at least two but no more than 10 decimal digits. (The decimal digits are 0, 1, ..., 9.) No digit appears more than once in one line of the input. The digits will appear in increasing order, separated by exactly one blank space.OutputFor each test case, write on a single line the smallest absolute difference of two integers that can be written from the given digits as described by the rules above.Sample Input
1
0 1 2 4 6 7
Sample Output
28


注意剪枝#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>

using namespace std;

int a[10];

int tn(int x,int y){
int ans=0;
for(int i=x;i<=y;i++){
ans*=10;
ans+=a[i];
}
return ans;
}

int main(){
int n;
cin>>n;
getchar();
while(n--){
string line;
getline(cin,line);

int index=0;
for(int i=0;i<line.length();i++){
if('0'<=line[i]&&line[i]<='9'){
a[index++]=line[i]-'0';
}
}

//for(int i=0;i<index;i++)cout<<a[i];
//cout<<endl;

int minn=999999999;
do{
for(int i=0;i<(index)/2;i++){
if(a[0]==0&&i!=0||a[i+1]==0&&(i!=index-2))continue;
minn=min(minn,abs(tn(0,i)-tn(i+1,index-1)));
}
}while(next_permutation(a,a+index));
cout<<minn<<endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: