之前百度编程题笔试做得还可以,发在了牛客网,但没发到CSDN,现在补一下
第一题,买饮料:
#include<cstdio>
using namespace std;
#define N 1100
#define K 1100
int n,k;
int like[N],buy_count[K]={0};
int main(){
int i,t,sum=0;
scanf("%d%d",&n,&k);
for(i=0;i<n;i++){
scanf("%d",&t);
buy_count[t]++;
}
for(i=1;i<=k;i++){
sum+=(buy_count[i]/2+buy_count[i]%2);
}
printf("%d\n",sum);
return 0;
}
第二题,分岔。比较坑,一开始以为是动态规划来着,结果发现直接搜索就可以了…幸好在交卷前1分钟试一下搜索发现可以,不然凉了…
#include<cstdio>
#include<map>
#include<unordered_map>
#include<queue>
using namespace std;
map<int,int> fork_count;//部队分开的数量
int n,k;
int main(){
int i,j,x,y,min_query;
queue<int> q;
int count=0,t;
scanf("%d%d",&n,&k);
q.push(n);
while(!q.empty()){
t=q.front();
q.pop();
if(t>k&&(t-k)%2==0){
//可分
x=(t-k)/2;
y=x+k;
q.push(x);
q.push(y);
}else count++;//不可分
}
printf("%d\n",count);
return 0;
}
第三题,拼火柴。用动态规划。比较坑的点一个是两个结果是要像字符串一样拼起来,例如123+456=123456;一个是要注意“火柴要全部用完”这个条件。
#include<cstdio>
#include<string>
#include<map>
using namespace std;
#define N 10010
int cost[10]={0,2,5,5,4,5,6,3,7,6};
int n,m;
string res[N]={""};
bool bigger(const string& x,const string& y){
if(x.size()!=y.size()) return x.size()>y.size();
else return x>y;
}
int main(){
char buf[5];
string sign;
int i,j,value;
int t_cost;
string x,y;
scanf("%d%d",&n,&m);
for(i=0;i<m;i++){
scanf("%s",buf);
sign=buf;
sscanf(buf,"%d",&value);
t_cost=cost[value];
//printf("sign=%s value=%d cost=%d\n",sign.c_str(),value,t_cost);
if(res[t_cost]!=""){
if(bigger(sign,res[t_cost])){
res[t_cost]=sign;
}
}else res[t_cost]=sign;
}
/*for(i=1;i<=9;i++){
printf("res[%d]=%s\n",i,res[i].c_str());
}*/
for(i=2;i<=n;i++){
for(j=0;j<=i;j++){
x=res[j];
y=res[i-j];
if(x!=""&&y!=""&&bigger(x+y,res[i])){
res[i]=x+y;
}
}
//printf("i=%d res=%s\n",i,res[i].c_str());
}
printf("%s\n",res[n].c_str());
return 0;
}
牛客网链接:https://www.nowcoder.com/discuss/382305?source_id=profile_create_nctrack&channel=-1