POJ 2718: Smallest Difference

Idea: Arrange all the numbers, then cut, calculate the absolute value of the difference between the two numbers, and constantly update the results

Use the next_permutation() function in the algorithm:
Usage:
next_permutation(start, end); (start and end are the head and tail pointers of the array respectively) The
function is to update the element order in the array and the lexicographic order of the new order It is the smallest of all the lexicographical arrangements greater than the original arrangement, that is, there is no arrangement x, so that the lexicographical order size is:
original arrangement<x<new arrangement

If the next permutation exists, that is, there is a permutation greater than the current permutation lexicographically, and the return value is true.
If the next permutation does not exist, it returns false

#include <cstdio>
#include <cstring>
#include <stack>
#include <queue> 
#include <algorithm> 
#include<iostream>
#include<map>
using namespace std;
#define MAX_A 10000


int main(){
    
    
	int t;
	scanf("%d",&t);
	getchar();
	int array[11];
	while(t--){
    
    
		int result = -1;//要输出的结果 
		//输入数组
		char c;
		int n = 0;
		while(1){
    
    
			scanf("%c",&c);
			if(c=='\n'){
    
    
				break;
			}else if(c==' '){
    
    
				continue;
			}else{
    
    
				array[n] = c-'0';
				n++;
			}
		}
		do{
    
    
			//把数切割成两个
			int a = 0,b = 0;
			int k;
			for(k=0;k<n/2;k++){
    
    
				a = a*10+array[k];
			} 
			for(k=n/2;k<n;k++){
    
    
				b = b*10+array[k];
			}
			//把开头为0的情况排除
			if((array[0]==0&&n/2!=1)||(array[n/2]==0&&(n-n/2)!=1)){
    
    
				continue;
			} 
			//得到两个数之差的绝对值
			int dif =  a-b;
			if(dif<0){
    
    
				dif = -dif;
			}
			if(result==-1||dif<result){
    
    
				result = dif;
			}
		}while(next_permutation(array,array+n));
		printf("%d\n",result);
	}
	
	return 0;
}

Guess you like

Origin blog.csdn.net/xiaobin_23134/article/details/115320488