状态转移方程: f [ i + 1 ] [ j + a [ i ] ] = m a x ( f [ i ] [ j ] ) , f [ i + 1 ] [ j + b [ i ] ] = m a x ( f [ i ] [ j ] + 1 ) f[i+1][j+a[i]]=max(f[i][j]),f[i+1][j+b[i]]=max(f[i][j]+1) f[i+1][j+a[i]]=max(f[i][j]),f[i+1][j+b[i]]=max(f[i][j]+1)
不翻和翻 再枚举最小值。
#include
#include
#include
using namespace std;
const int inb=2139062143;
int a[1001],b[1001],s,n,f[1001][6001];
int main(){
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d%d",&a[i],&b[i]),s+=a[i]+b[i];
memset(f,127,sizeof(f)); f[1][0]=0;
for (int i=1;i<=n;i++)
for (int j=0;j<=i*6;j++)
if (f[i][j]<inb){
f[i+1][j+a[i]]=min(f[i+1][j+a[i]],f[i][j]);
f[i+1][j+b[i]]=min(f[i+1][j+b[i]],f[i][j]+1);
}//状态转移方程
int ans=inb,flag;
for (int i=0;i<=n*6;i++)
if (f[n+1][i]<inb&&abs(s-2*i)<ans||abs(s-2*i)==ans&&flag>f[n+1][i]) ans=abs(s-2*i),flag=f[n+1][i];//计算最小值
printf("%d",flag);
return 0;
}