题目来源2018年华南理工大学校赛https://www.nowcoder.com/acm/contest/94/K
题目分析:
一共有35瓶药水直接暴力枚举肯定超时,但是这个数据有不是很大,18瓶药水枚举也只有20w种情况,所以考虑用二分法来优化暴力枚举。根据浓度关系是可以得出:当满足x*b-y*a==-x*b+y*a的时候可以配出符合浓度要求的药水,那么先枚举出20种配比存在哈希表里面,右边再根据配比在哈希表中找有没有符合要求的药水集合。特别要注意的是,如果左边和右边都是空集,即0==0,也被算入了答案,所以最后ans要-1。
AC代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Main{
static InputReader input = new InputReader();
static PrintWriter out = new PrintWriter(System.out);
static HashMap<Long,Integer> map;
static int[] A;
static int[] B;
static long a;
static long b;
static int m;
static int n;
static long ans;
public static void main(String[] args){
int count = input.nextInt();
for(int i=0;i<=count-1;i++){
map = new HashMap();
n = input.nextInt();
a = input.nextLong();
b = input.nextLong();
m = n/2;
ans = 0;
A = new int[n];
B = new int[n];
for(int j=0;j<=n-1;j++){
A[j] = input.nextInt();
B[j] = input.nextInt();
}
dfs1(0,0,0);
dfs2(m,0,0);
out.println(ans-1);//去除掉两遍都是0的情况
}
out.close();
}
static void dfs1(int i,long x,long y){
if(i==m){
if(map.get(x*b-y*a)==null){
map.put(x*b-y*a,1);
}else{
map.put(x*b-y*a,map.get(x*b-y*a)+1);
}
return;
}
dfs1(i+1,x,y);
dfs1(i+1,x+A[i],y+B[i]);
}
static void dfs2(int i,long x,long y){
if(i==n){
if(map.get(-x*b+y*a)!=null){
ans += map.get(-x*b+y*a);
}
return;
}
dfs2(i+1,x,y);
dfs2(i+1,x+A[i],y+B[i]);
}
static class InputReader
{
BufferedReader buf;
StringTokenizer tok;
InputReader()
{
buf = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext()
{
while(tok == null || !tok.hasMoreElements())
{
try
{
tok = new StringTokenizer(buf.readLine());
}
catch(Exception e)
{
return false;
}
}
return true;
}
String next()
{
if(hasNext()) return tok.nextToken();
return null;
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
BigInteger nextBigInteger()
{
return new BigInteger(next());
}
BigDecimal nextBigDecimal()
{
return new BigDecimal(next());
}
}
}