第十二届蓝桥杯 砝码称重
暴搜 只能过50%
import java.util.*;
public class Main
{
static int n,N=100005,ans;
static boolean st[]=new boolean [N];
static boolean us[]=new boolean [N];
static int a[]=new int [N];
static void dfs(int t,int from,int p)
{
if(t==n+1)return;
for(int i=from;i<n;++i)
{
if(us[i]==false)
{
us[i]=true;
int d=Math.abs(p-a[i]);
st[p+a[i]]=true;
dfs(t+1,i+1,p+a[i]);
st[d]=true;
dfs(t+1,i+1,d);
us[i]=false;
}
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
for(int i=0;i<n;++i)
{
a[i]=sc.nextInt();st[a[i]]=true;
}
dfs(1,0,0);
for(int i=1;i<N;++i)
if(st[i])ans++;
System.out.println(ans);
}
}
模拟可以AC,因为给定条件说了砝码总的重量在10^5内
import java.util.*;
public class Main
{
static int n,N=100005,ans;
static boolean st[]=new boolean [N],backup[]=new boolean[N];
static int a[]=new int [N];
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
for(int i=0;i<n;++i)
{
a[i]=sc.nextInt();
}
for(int i=0;i<n;++i)
{
backup=st.clone();
for(int j=1;j<N;++j)
{
if(backup[j]==true)
{
int d=Math.abs(j-a[i]);
st[j+a[i]]=true;
st[d]=true;
}
}
st[a[i]]=true;
}
for(int i=1;i<N;++i)
if(st[i])ans++;
System.out.println(ans);
}
}
DP
import java.util.*;
public class Main
{
static int N=105,M=200005,S=M/2;
static boolean f[][]=new boolean [N][M];
static int w[]=new int [N];
static int n,m,ans;
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
for(int i=1;i<=n;++i)
{
w[i]=sc.nextInt();
m+=w[i];
}
f[0][S]=true;
for(int i=1;i<=n;++i)
{
for(int j=-m;j<=m;++j)
{
f[i][j+S]=f[i-1][j+S];
if(j-w[i]+S>=0)f[i][j+S]|=f[i-1][j+S-w[i]];
if(j+w[i]+S<M)f[i][j+S]|=f[i-1][j+S+w[i]];
}
}
for(int i=1;i<=m;++i)
if(f[n][i+S])ans++;
System.out.println(ans);
}
}