小易去附近的商店买苹果,奸诈的商贩使用了捆绑交易,只提供6个每袋和8个每袋的包装(包装不可拆分)。
可是小易现在只想购买恰好n个苹果,小易想购买尽量少的袋数方便携带。如果不能购买恰好n个苹果,小易将不会购买。输入描述: 输入一个整数n,表示小易想购买n(1 ≤ n ≤ 100)个苹果
输出描述: 输出一个整数表示最少需要购买的袋数,如果不能买恰好n个苹果则输出-1
输入例子: 20
输出例子: 3
动态规划:
f
(
x
)
f(x)
f(x)表示买
x
x
x个苹果最少需要购买的袋数
f
(
6
)
=
f
(
8
)
=
1
f(6)=f(8)=1
f(6)=f(8)=1
f
(
1
)
=
f
(
2
)
=
f
(
3
)
=
.
.
.
=
f
(
7
)
=
−
1
f(1)=f(2)=f(3)=...=f(7)=-1
f(1)=f(2)=f(3)=...=f(7)=−1
f
(
x
)
=
m
i
n
{
f
(
x
−
6
)
+
1
若
f
(
x
−
6
)
!
=
1
f
(
x
−
8
)
+
1
若
f
(
x
−
8
)
!
=
1
f(x)=min\left \{ \begin{aligned} f(x-6)+1 \hspace{1cm} 若f(x-6)!=1\\ f(x-8)+1 \hspace{1cm} 若f(x-8)!=1\\ \end{aligned} \right.
f(x)=min{f(x−6)+1若f(x−6)!=1f(x−8)+1若f(x−8)!=1
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
void solution(int n){
// TODO: 请在此编写代码
std::vector<int> res(108, -1);
res[6] = 1;
res[8] = 1;
if (n < 10){
std::cout << res[n] << std::endl;
}
else{
for (int i = 9; i < n+1; i++){
if (res[i - 6] != -1){
res[i] = res[i - 6] + 1;
}
if(res[i - 8] != -1){
if (res[i] != -1){
res[i] = std::min(res[i - 8] + 1, res[i]);
}
else{
res[i] = res[i - 8] + 1;
}
}
}
std::cout << res[n] << std::endl;
}
}
int main() {
int n;
scanf("%d", &n);
solution(n);
return 0;
}