首页 > 代码库 > POJ-2718
POJ-2718
Smallest Difference
Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 12158 Accepted: 3306 Description
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
The 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.Output
For 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
10 1 2 4 6 7Sample Output
28
题意:
将所给出的所有数字排列组合生成两个数,使其差的绝对值最小。求最小值。
贪心可做,学到了一种STL求全排列的方法:next_permutation();
AC代码:
1 //#include<bits/stdc++.h> 2 #include<algorithm> 3 #include<iostream> 4 #include<cstring> 5 #include<cstdio> 6 #include<cmath> 7 using namespace std; 8 9 const int INF=1<<30;10 char str[30];11 int num[15];12 13 int main(){14 int n;15 cin>>n;16 getchar();17 while(n--){18 int res=INF;19 gets(str);//得到数列 20 int len=strlen(str);21 int k=0;22 for(int i=0;i<len;i++){23 if(str[i]>=‘0‘&&str[i]<=‘9‘){24 num[k++]=str[i]-‘0‘;25 }26 }27 if(k==2){//如果只有两个数的情况 28 cout<<abs(num[0]-num[1])<<endl;29 continue;30 }31 while(num[0]==0){//不能含有前导零 32 next_permutation(num,num+k);33 }34 //int ans=INF;35 do{36 int mid=(k+1)/2;37 if(num[mid]){//第二个数也不能有前导零 38 int a=0,b=0;39 for(int i=0;i<mid;i++){40 a=a*10+num[i];41 }42 for(int i=mid;i<k;i++){43 b=b*10+num[i];44 }45 res=min(res,abs(a-b));46 }47 48 }while(next_permutation(num,num+k));49 cout<<res<<endl;50 }51 return 0;52 }
POJ-2718
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。