abc375E
作者:
Air1222
,
2024-10-17 22:12:30
,
所有人可见
,
阅读 2
//暴力
#include <iostream>
#include <cstring>
using namespace std;
const int N = 110,M = 50;
int f[N][M][M][M];//f[i][j][k][d]=min(f[i-1][j-b[i]][k][d],f[i-1][j][k-b[i]][j][d])
int a[N];
int b[N];
int sum=0;
int main()
{
memset(f,0x3f,sizeof f);
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i]>>b[i];
sum+=b[i];
}
if(sum%3!=0) cout<<"-1"<<endl;
else
{
f[0][0][0][0]=0;
for(int i=1;i<=n;i++)
for(int j=0;j<=sum/3;j++)
for(int k=0;k<=sum/3;k++)
for(int l=0;l<=sum/2;l++)
{
if(j>=b[i]) f[i][j][k][l]=f[i-1][j-b[i]][k][l]+1-(a[i]==1);
if(k>=b[i]) f[i][j][k][l]=min(f[i][j][k][l],f[i-1][j][k-b[i]][l]+1-(a[i]==2));
if(l>=b[i]) f[i][j][k][l]=min(f[i][j][k][l],f[i-1][j][k][l-b[i]]+1-(a[i]==3));
}
cout<<f[n][sum/3][sum/3][sum/3]<<endl;
}
return 0;
}
//错误代码
//不能去掉一维,因为当前本身就去掉一维,f[i][j]一定被当前维度更新
//后面更新的就错误了
#include <iostream>
#include <cstring>
using namespace std;
const int N = 110,M = 510;
int f[M][M];//f[i][j][k][d]=min(f[i-1][j-b[i]][k][d],f[i-1][j][k-b[i]][j][d])
int a[N];
int b[N];
int s[N];
int sum=0;
int main()
{
memset(f,0x3f,sizeof f);
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i]>>b[i];
sum+=b[i];
s[i]=s[i-1]+b[i];
}
if(sum%3!=0) cout<<"-1"<<endl;
else
{
f[0][0]=0;
for(int i=1;i<=n;i++)
for(int j=sum/3;j>=0;j--)
for(int k=sum/3;k>=0;k--)
{
if(s[i]-j-k>=b[i]) f[j][k]=min(f[j][k],f[j][k]+1-(a[i]==3));
if(j>=b[i]) f[j][k]=min(f[j][k],f[j-b[i]][k]+1-(a[i]==1));
if(k>=b[i]) f[j][k]=min(f[j][k],f[j][k-b[i]]+1-(a[i]==2));
}
if(f[sum/3][sum/3]==0x3f3f3f3f)cout<<"-1";
else cout<<f[sum/3][sum/3]<<endl;
}
return 0;
}
//当j,k固定时,l则固定,因此可以用前缀和优化掉一维
//注意不一定为0x3f3f3f3f可能大于0x3f3f3f3f
#include <iostream>
#include <cstring>
using namespace std;
const int N = 110,M = 510;
int f[N][M][M];//f[i][j][k][d]=min(f[i-1][j-b[i]][k][d],f[i-1][j][k-b[i]][j][d])
int a[N];
int b[N];
int s[N];
int sum=0;
int main()
{
memset(f,0x3f,sizeof f);
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i]>>b[i];
sum+=b[i];
s[i]=s[i-1]+b[i];
}
if(sum%3!=0) cout<<"-1"<<endl;
else
{
f[0][0][0]=0;
for(int i=1;i<=n;i++)
for(int j=0;j<=sum/3;j++)
for(int k=0;k<=sum/3;k++)
{
if(j>=b[i]) f[i][j][k]=f[i-1][j-b[i]][k]+1-(a[i]==1);
if(k>=b[i]) f[i][j][k]=min(f[i][j][k],f[i-1][j][k-b[i]]+1-(a[i]==2));
if(s[i]-j-k>=b[i]) f[i][j][k]=min(f[i][j][k],f[i-1][j][k]+1-(a[i]==3));
}
if(f[n][sum/3][sum/3]>0x3f3f3f3f)cout<<"-1";
else cout<<f[n][sum/3][sum/3]<<endl;
}
return 0;
}