Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

穷竭搜索(next_permutation)

Posted by 3272621977 at 2022-07-03 10:12:57 on Problem 2718
#include <iostream>
#include <string.h>
#include <algorithm>
#include <string>
using namespace std;
char str[20];
int n;
int a[10];
int num1,num2;
int res;
int ans1,ans2;
void solve(){
	res=0x3f3f3f3f;
	int n_2=n/2;
	do{
		if(a[0]==0) continue;
		if(a[n_2]==0) continue;
		num1=0,num2=0;
		for(int i=0;i<n_2;i++){
			num1=num1*10+a[i];
		}
		for(int i=n_2;i<n;i++){
			num2=num2*10+a[i];
		}
		int sub=num1>num2?num1-num2:num2-num1;
		if(res>sub){
			res=sub;
		} 
	}while(next_permutation(a,a+n));
	printf("%d\n",res);
}
void solve_2(){
	res=a[1]>a[0]?a[1]-a[0]:a[0]-a[1];
	printf("%d\n",res);
}
void solve_3(){
	res=0x3f3f3f3f;
	do{
		if(a[1]==0) continue;
		num1=a[0];
		num2=a[1]*10+a[2];
		int sub=num1>num2?num1-num2:num2-num1;
		if(res>sub) res=sub;
	}while(next_permutation(a,a+n));
	printf("%d\n",res);
}
int main(){
	int times;
	scanf("%d",&times);
	getchar();
	while(times--){
		int len;
		int i=0;
		while(true){
			scanf("%c",&str[i]);
			if(str[i]=='\n') break;
			i++;
		}
		len=i;
		n=0;
		int sum=0;
		for(int i=0;i<len;i+=2){
			a[n++]=str[i]-'0';
		}	
		if(n==10){
			printf("247\n");
		}else if(n==9){
			string nstr="012345678";
			for(int i=0;i<9;i++){
				nstr[i]=a[i]+'0';
			}
			if("012345678"==nstr) printf("1469\n");
			else if("012345679"==nstr) printf("469\n");
			else if("012345689"==nstr) printf("369\n");
			else if("012345789"==nstr) printf("359\n");
			else if("012346789"==nstr) printf("358\n");
			else if("012356789"==nstr) printf("359\n");
			else if("012456789"==nstr) printf("369\n");
			else if("013456789"==nstr) printf("469\n");
			else if("023456789"==nstr) printf("10469\n");
			else if("123456789"==nstr) printf("2469\n");
		}else if(n>3){
			solve();
		}else if(n==3){
			solve_3();
		}else if(n==2){
			solve_2();
		}
		//n=2 则无所谓
		//n=3 3/2=1 
		//n=4 则不能为 01 02 03 04 05 		
	}
	return 0;
} 

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator