全排列水题 Smallest Difference

Smallest Difference

题意:将n个数字分为两组,怎么分两组之差最小 忘记为啥这么写了,暴力最容易就是了_(:з」∠)_

//A
#include<iostream>
#include<sstream>
#include<algorithm>
#include<string.h>
#include<cmath>
#include<stdio.h>
using namespace std;
int a[15];
char s[30];

int solve(int num)
{
    int ans=0x3f3f3f3f;
   // while(a[0]==0) next_permutation(a,a+num);
    do
    {
        if(a[0]==0) continue;
        int mid=(num+1)/2;
        if(a[mid]==0) continue;

        int x=0;
        int y=0;
        for(int i=0;i<mid;++i)
            x=x*10+a[i];
        for(int j=mid;j<num;++j)
            y=y*10+a[j];
        ans=min(ans,abs(y-x));
    }while(next_permutation(a,a+num));
    return ans;
}
int main()
{
    int n;
    cin>>n;
    getchar();
    while(n--)
    {
        gets(s);//读取一行
        int len=strlen(s);
        int num=0;
        for(int i=0;i<len;++i)
        {
            if(s[i]>='0'&&s[i]<='9')
                a[num++]=s[i]-'0';
        }
        if(num==2)
        {
            cout<<a[1]-a[0]<<endl;
            continue;
        }
        int ans=0;
        ans=solve(num);
        cout<<ans<<endl;
    }


}

 

猜你喜欢

转载自blog.csdn.net/iroy33/article/details/88622257
0条评论
添加一条新回复
  
今日推荐