题目
Source
http://acm.hdu.edu.cn/showproblem.php?pid=5937
Description
Little Ruins is a studious boy, recently he learned addition operation! He was rewarded some number bricks of 1 to 9 and infinity bricks of addition mark '+' and equal mark '='.
Now little Ruins is puzzled by those bricks because he wants to put those bricks into as many different addition equations form x+y=z as possible. Each brick can be used at most once and x, y, z are one digit integer.
As Ruins is a beginer of addition operation, x, y and z will be single digit number.
Two addition equations are different if any number of x, y and z is different.
Please help little Ruins to calculate the maximum number of different addition equations.
Input
First line contains an integer T, which indicates the number of test cases.
Every test case contains one line with nine integers, the ith integer indicates the number of bricks of i.
Limits
1≤T≤30
0≤bricks number of each type≤100
Output
For every test case, you should output 'Case #x: y', where x indicates the case number and counts from 1 and y is the result.
Sample Input
3
1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
0 3 3 0 3 0 0 0 0
Sample Output
Case #1: 2
Case #2: 6
Case #3: 2
分析
题目大概说有若干个1到9这几个数字问最多能拼成多少种x+y=z的等式?
- x+y=z有36种。由于x>y和x<y是对称的,只考虑x<=y,有20种,16种是x<y,4种x=y。。
- 直接暴力搜索。。对于x<y,可以选1种、选2种和不选;对于x=y可以选和不选。
- 那么这样时间复杂度是$O(3^{16}*2^4)$。。
- 不剪枝会超时的,我加了几个预测的最优性剪枝,利用剩下的各个数字的个数粗略估算最多还能加入几种等式。。
- 实测100 100 100 100 100 100 100 100 100 100秒出= =。。
代码
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int x[]={1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,4}; int y[]={2,3,4,5,6,7,8,3,4,5,6,7,4,5,6,5}; int z[]={3,4,5,6,7,8,9,5,6,7,8,9,7,8,9,9}; int x2[]={1,2,3,4}; int y2[]={2,4,6,8}; int a[11],ans; void dfs2(int k,int n){ if(ans<n) ans=n; if(k==4) return; if(a[x2[k]]>1 && a[y2[k]]){ a[x2[k]]-=2; --a[y2[k]]; dfs2(k+1,n+1); a[x2[k]]+=2; ++a[y2[k]]; } dfs2(k+1,n); } inline calc(int a,int b){ if(a<b) return a<<1; return b<<1; } void dfs(int k,int n){ if(k<=7){ if(n+4+calc(a[1],7-k)+calc(a[2],5)+calc(a[3],3)+calc(a[4],1)<ans) return; }else if(k<=12){ if(n+4+calc(a[2],12-k)+calc(a[3],3)+calc(a[4],1)<ans) return; }else{ if(n+4+calc(a[3],15-k)+calc(a[4],1)<ans) return; } if(k==16){ dfs2(0,n); return; } dfs(k+1,n); if(((x[k]==y[k]&&a[x[k]]>1) || (x[k]!=y[k]&&a[x[k]])) && a[y[k]] && a[z[k]]){ --a[x[k]]; --a[y[k]]; --a[z[k]]; dfs(k+1,n+1); ++a[x[k]]; ++a[y[k]]; ++a[z[k]]; } if(x[k]!=y[k] && a[x[k]]>1 && a[y[k]]>1 && a[z[k]]>1){ a[x[k]]-=2; a[y[k]]-=2; a[z[k]]-=2; dfs(k+1,n+2); a[x[k]]+=2; a[y[k]]+=2; a[z[k]]+=2; } } int main(){ int t; scanf("%d",&t); for(int cse=1; cse<=t; ++cse){ for(int i=1; i<=9; ++i){ scanf("%d",a+i); } ans=0; dfs(0,0); printf("Case #%d: %d\n",cse,ans); } return 0; }
来源:https://www.cnblogs.com/WABoss/p/6044521.html