链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
题目描述
牛牛有x件材料a和y件材料b,用2件材料a和3件材料b可以合成一件装备,用4件材料a和1件材料b也可以合成一件装备。牛牛想要最大化合成的装备的数量,于是牛牛找来了你帮忙。
输入描述:
输入包含t组数据 第一行一个整数t 接下来t行每行两个整数x,y
输出描述:
每组数据输出一行一个整数表示答案。
示例1
输入
5 4 8 7 6 8 10 100 4555 45465 24124
输出
2 2 3 50 13917
备注:
1<=t<=10000
1<=x,y<=1e9
法一:
三分:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll t,x,y;
ll df(ll g){
return g+min((x-4*g)/2,(y-g)/3);
}
int main()
{
cin>>t;
while(t--){
cin>>x>>y;
ll l=0,r=min(x/4,y);
while((r-l)>10){
ll s1=l+(r-l)/3,s2=r-(r-l)/3;
if(df(s1)>df(s2)) r=s2;
else l=s1;
}
ll ans=0;
for(int i=l;i<=r;++i) ans=max(ans,df(i));
cout<<ans<<endl;
}
return 0;
}
法二:
线性规划 运筹
高中基础知识的运用,但是要注意每次特判极值点附近的几个整数,因为普通的线性规划返回的只是实数;
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll t,x,y;
int main()
{ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin>>t;
while(t--){
cin>>x>>y;
if((4*y>x)&&(4*y<6*x)){
double n=(3*x-2*y)/10.00;
double m = (4 * y - x) / 10.00;
ll n_floor = floor(n);
ll m_floor = floor(m);
ll n_ceil = ceil(n);
ll m_ceil = ceil(m);
if ((2*m_ceil+4*n_ceil<=x)&&(3*m_ceil+n_ceil<=y)) cout<<m_ceil+n_ceil<<endl;
else if ((2*m_ceil+4*n_floor<=x)&&(3*m_ceil+n_floor<=y)) cout<<m_ceil+n_floor<<endl;
else if ((2*m_floor+4*n_ceil<=x)&&(3*m_floor+n_ceil<=y)) cout<<m_floor+n_ceil<<endl;
else if ((2*m_floor+4*n_floor<=x)&&(3*m_floor+n_floor<=y)) cout<<m_floor+n_floor<<endl;
continue;
}
else if(2*y>=3*x){
cout<<x/2<<endl;
continue;
}
else cout<<y<<endl;
}
return 0;
}
法三:
二分:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll t,x,y;
bool judge(ll ans){
ll s1=max((ll)0,4*ans-x);//0强制转换类型,保证max函数的使用
ll s2=min(2*ans,y-ans);
if(s1==s2&&(s1&1)) return false;
else if(s1>s2) return false;
return true;
}
int main()
{
cin>>t;
while(t--){
cin>>x>>y;
ll l=1,r=y;
while(l<=r){
ll mid=(l+r)/2;
if(judge(mid)) l=mid+1;
else r=mid-1;
}
cout<<l-1<<endl;
}
return 0;
}
都挺好的,思路各不相同。