我有一个任务,听起来是这样的:“一个弓箭手有黑白箭头,他只能用白色箭头射出白色鸭子,黑色箭头只能射出黑色鸭子。鸭子分成几组,它们的大小是这样的:一,二,三,五,八等等,所以基本上是斐波纳契数。这些组中的鸭子被排序,这样你就不会发现两只颜色相同的鸭子在彼此附近,每一组都以一只白色的鸭子开始(例如,对于有5只鸭子的那组:白色的、黑色的、黑色的)。弓箭手只有杀死整群鸭子,才能杀死鸭子。“
如果给出白色箭头(Ka)和黑色箭头(Kb)的数量,我必须说明射手杀死了多少组,以及每种类型的箭头有多少只剩下。
int ka, kb;
cin >> ka >> kb;
int total_rows{0};
for(int current_group{1}, previous_group{1}; ka+kb >= current_group; ++total_rows)
{
//see which of the arrows he shoots
for(int i=1; i <= current_group; ++i)
{
if(i%2 == 1)
--ka;
else
--kb;
}
// swap the 2 fib numbers so we can get the next one
swap(current_group, previous_group);
current_group += previous_group;
}
cout << total_rows << ' ' << ka << ' ' << kb; 如果我打字,例如9和10,我应该得到4,2,6。我得到了一些与此无关的东西.
发布于 2017-12-08 19:58:02
也许是一种稍微不同的方法来计算将使用多少箭头,而不是您正在使用的箭头。我们知道鸭子是交替的,这意味着对于奇数组,你需要额外的白色箭头,否则每种颜色使用的数字都是N/2。
#include <iostream>
int next_group()
{
static int prev = 0;
static int next = 1;
int res = prev + next;
prev = next;
next = res;
return next;
}
int main()
{
int white, black;
std::cin >> white >> black;
int groups = 0;
while (true)
{
int n = next_group();
int arrows = n % 2 == 0 ? n / 2 : (n - 1) / 2;
if (n % 2 == 0)
{
if (arrows > white || arrows > black)
break;
}
else
{
if (arrows + 1 > white || arrows > black)
break;
white--;
}
white -= arrows;
black -= arrows;
groups++;
}
std::cout
<< "Complete groups eliminated: " << groups
<< "\nWhite arrows left: " << white
<< "\nBlack arrows left: " << black
<< std::endl;
system("pause");
return 0;
}

https://stackoverflow.com/questions/47720623
复制相似问题