HNU Digit Sum (状态压缩)

Digit Sum
Time Limit: 2000ms, Special Time Limit:5000ms, Memory Limit:65536KB
Total submit users: 69, Accepted users: 61
Problem 12944 : No special judgement
Problem description

When Grace was in third grade, her elementary school teacher assigned her the following problem:

What is the smallest possible sum of two numbers that together use the numerals 1, 2, 7, 8, and 9?

Grace figured out that the answer to this problem is 207 (for example, as 78 + 129), but when the teacher assigned four pages of similar problems as homework, Grace got bored. It turns out that Grace was a rather advanced third grader, so she decided that it would be more fun to write a computer program to solve such problems. Surely you can do the same!


Input

Input:  Each problem is described on a single line. The line begins with an integer N, such that 2 ≤ N ≤ 14 , designating the number of numerals included in the problem. Following that are those N numerals. There will always be at least 2 numerals that are nonzero. The end of the input is designated by a line containing only the value 0.


Output

Output:  For each case, output a line with the minimum sum S that can be achieved. Please keep in mind that by standard convention, the numeral 0 cannot appear as the first digit of either summand.


Sample Input
5 1 2 7 8 9
6 3 4 2 2 2 2
9 0 1 2 3 4 0 1 2 3
0
Sample Output
207
447
11257
Problem Source
ACM Mid-Central Programming Competition 2013

#include<stdio.h>
#include<algorithm>
using namespace std;
#define mulit(i) (1<<(i))
__int64 a[15],sta[mulit(14)];
void init(int n)
{
    __int64 sum;
    int h,i;
    sort(a,a+n);
    for(int s=1;s<mulit(n);s++)
    {
        h=-1;
        for( i=0;mulit(i)<=s;i++)
        if((mulit(i)&s)&&a[i]>0)
        {
            h=i; sum=a[i]; break;
        }
        if(mulit(i-1)==s)
        {
            sta[s]=a[i-1]; continue;
        }
        if(mulit(i)>s)
        {
            sta[s]=-1; continue;
        }
        for( i=0;mulit(i)<=s;i++)
        if((mulit(i)&s)&&h!=i)
        sum=sum*10+a[i];
        sta[s]=sum;
    }
}
int main()
{
    int n;
    __int64 minsum;
    while(scanf("%d",&n)>0&&n)
    {
        for(int i=0;i<n;i++)
        scanf("%I64d",&a[i]);
        init(n);
        minsum=-1;
        for(int s=1;s<mulit(n);s++)
        if(sta[s]!=-1&&sta[s^(mulit(n)-1)]!=-1)
        if(minsum==-1)
            minsum=sta[s]+sta[s^(mulit(n)-1)];
        else if(minsum>sta[s]+sta[s^(mulit(n)-1)])
            minsum=sta[s]+sta[s^(mulit(n)-1)];
        printf("%I64d\n",minsum);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值