暴搜一下就行了,确实也没法优化什么。 不过枚举一半,另一半用next_permutation()函数应该是会快一些的。
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<queue> #include<cmath> using namespace std; int T,a[20],n,vis[20],tot; int A[20],B; void dfs(int cur) { if(cur==n/2) { int b[20],kase = 0; for(int i=0;i<n;i++) { if(!vis[i]) b[kase++] = a[i]; } sort(b,b+kase); do { int t=0; if(b[0]==0&&n-cur>1) continue; for(int i=0;i<kase;i++) t = t*10 + b[i]; int c = abs(t-B); if(c<tot) tot = c; } while(next_permutation(b,b+kase)); } else for(int i=0;i<n;i++) { if(cur==0&&a[i]==0) continue; if(!vis[i]) { B=B*10+a[i]; A[cur] = a[i]; vis[i] = 1; dfs(cur+1); B = (B-a[i])/10; vis[i] = 0; } } } int main() { scanf("%d",&T); char c = getchar(); while(T--) { char s[100]; int kase = 0; gets(s); n = strlen(s); for(int i=0;i<n;i++) { if(s[i]!=' ') { a[kase++] = s[i]-'0'; } } n = kase; memset(vis,0,sizeof(vis)); memset(A,0,sizeof(A)); B = 0; tot = 1000000000; dfs(0); printf("%d\n",tot); } return 0; }
原文地址:http://blog.csdn.net/weizhuwyzc000/article/details/45043027