一、柠檬水找零Pro08
样例输入
5 5 5 10 20
样例输出
true
样例输入
5 5 10 10 20
样例输出
false
思路分析:
法一:蛮力法。用三个整数来记录按顺序找零过程中三个数额的钞票数量,然后模拟按顺序找零的过程即可,这里需要注意以下20找零的顺序。
AC代码(蛮力):
#include<bits/stdc++.h>
#define N 100000
using namespace std;
int main(){
int bills[N]={0};
int len = 0;
while(cin>>bills[len]){
len++;
}
int flag = true;//是否能否成功找零
int five,ten,tw;//存储三个数额的钞票数量
five=ten=tw=0;
for(int i=0 ; i<len ; i++){
if(bills[i]==5)
five++;
else if(bills[i]==10){
if(five!=0){
five--;
ten++;
}
else{
flag=false;
break;
}
}
else if(bills[i]==20){
//优先用10找零,留着5(因为5既可以给10找零也可以给20找零,而10只可以给20找零)
if(five>=1&&ten>=1){
five--;
ten--;
tw++;
}
//如果没有10就用3张5
else if(five>=3){
five = five-3;
tw++;
}
else{
flag=false;
break;
}
}
}
if(flag)
cout<<"true";
else
cout<<"false";
return 0;
}
二、种花问题Pro09
样例输入
1 0 0 0 1
2
样例输出
false
思路分析:
①从左到右扫描数组 flowerbed,如果数组中有一个 0,并且这个 0 的左右两侧都是 0,那么我们就可以在这个位置种花,将这个位置对应的数值修改成 1,剩余需要插入的花的数量减一;
②对于数组的第一个和最后一个位置,我们只需要考虑一侧是否为 0;
③在扫描结束之后,看剩余未栽种的数量n是否为0,如果 n=0,那么返回 True,否则返回 False;
④此外还需要注意一点很坑的地方,即数据的输入,在本校的OJ系统上给的案例是空格+'\n’结束输入的(可能是),不是简单的回车结束输入,如下:
if(cin.get()==‘\n’) break;
最好是将整行的输入读入,如下面的AC代码所示,利用字符串流读入数据。
AC代码(蛮力):
#include<bits/stdc++.h>
#define N 20000
using namespace std;
int main(){
int flowerbed[N]={0};
int i=0;
int tmp;
string str;
getline(cin,str);//按行读取
stringstream ss(str);//字符串流
while(ss>>tmp){
flowerbed[i] = tmp;
i++;
}
int n;
cin>>n;//需要插入多少朵花
for(int j=0 ; j<i ; j++){
//注意要考虑第一个和最后一个位置的情况
if(flowerbed[j] == 0 && (j == 0 || flowerbed[j - 1] == 0) && (j == i - 1 || flowerbed[j + 1] == 0)){
n--;
flowerbed[j] = 1;
}
}
if(n>0)
cout<<"false";
else
cout<<"true";
return 0;
}
三、买鸡问题Pro30
样例输入
100 100
样例输出
0 25 75
4 18 78
8 11 81
12 4 84
样例输入
10 100
样例输出
0
样例输入
50 50
样例输出
2 9 39
6 2 42
AC代码(蛮力):
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,k;
cin>>n>>k;
int flag=0;
int a,b,c;
for(a=0 ; a<=n/5 ; a++){
for(b=0 ; b<=n/3 ; b++){
for(c=0 ; c<=n ; c++){
if((a+b+c==k)&&(5*a+3*b+c/3==n)&&c%3==0){
if(flag!=0)
cout<<endl;//由于最后一行输出后不换行,所以提前输出换行
cout<<a<<" "<<b<<" "<<c;
flag=1;
}
}
}
}
if(flag==0)
cout<<0;
return 0;
}