放苹果c++

题目:

思路:设i为苹果数  k为盘子数
当i<k: 把i个苹果放到k-1个盘子里(因为k>i)所以至少有一个空盘子 所以此时f(i,k)=f(i,k-1)
当k<i时:是苹果多   f(i-k,k)是把多出来的苹果进行分放

#include <iostream>
using namespace std;
int N;
int f(int i, int k)//求放苹果分法 i为苹果  k为盘子
{
	if (i < k) return f(i,i);
	if (i == 0) return 1;
	if (k == 0) return 0;
	return f(i, k - 1) + f(i - k, k);
}
int main()
{
	int t,i,k;
	cin >> t;
	while (t--)
	{
		cin >> i >> k;//不断录入当前苹果和盘子数量
		cout << f(i, k) << endl;
	}
	return 0;
}

样例:

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用C++实现的爸爸苹果、妈妈橘子、儿子吃橘子、女儿吃苹果问题的P/V经典操作: ```c++ #include <iostream> #include <thread> #include <mutex> #include <condition_variable> using namespace std; mutex mtx; condition_variable cv; int apple = 0, orange = 0; void father() { for (int i = 0; i < 5; ++i) { unique_lock<mutex> lck(mtx); while (apple + 1 > 3) { // 苹果数超过3个就等待 cv.wait(lck); } ++apple; // 苹果 cout << "Father put an apple." << endl; cv.notify_all(); // 通知其他线程有新水果入 } } void mother() { for (int i = 0; i < 5; ++i) { unique_lock<mutex> lck(mtx); while (orange + 1 > 3) { // 橘子数超过3个就等待 cv.wait(lck); } ++orange; // 橘子 cout << "Mother put an orange." << endl; cv.notify_all(); // 通知其他线程有新水果入 } } void son_eat_orange() { for (int i = 0; i < 5; ++i) { unique_lock<mutex> lck(mtx); while (orange < 1) { // 没有橘子就等待 cv.wait(lck); } --orange; // 吃一个橘子 cout << "Son ate an orange." << endl; cv.notify_all(); // 通知其他线程有水果被取走 } } void daughter_eat_apple() { for (int i = 0; i < 5; ++i) { unique_lock<mutex> lck(mtx); while (apple < 1) { // 没有苹果就等待 cv.wait(lck); } --apple; // 吃一个苹果 cout << "Daughter ate an apple." << endl; cv.notify_all(); // 通知其他线程有水果被取走 } } int main() { thread father_thread(father); thread mother_thread(mother); thread son_thread(son_eat_orange); thread daughter_thread(daughter_eat_apple); father_thread.join(); mother_thread.join(); son_thread.join(); daughter_thread.join(); return 0; } ``` 在上述代码中,我们使用了互斥锁和条件变量来实现线程间的同步。其中,`father()`和`mother()`函数分别代表父亲和母亲水果的线程,`son_eat_orange()`和`daughter_eat_apple()`函数分别代表儿子和女儿吃水果的线程。在`father()`和`mother()`函数中,每次水果之前都会检查当前水果数量是否已经超过3个,如果超过了就等待其他线程取走一些水果后再入新的水果;在`son_eat_orange()`和`daughter_eat_apple()`函数中,每次吃水果之前都会检查当前是否还有水果可吃,如果没有就等待其他线程入新的水果。每次有水果被入或被取走时,都会通过条件变量通知其他线程。最后,我们启动了4个线程,并使用`join()`函数等待所有线程执行完毕后退出程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值