Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ เช็คว่าซื้อสินค้าด้วยเงินที่กำหนดได้หรือไม่


สมมติว่าเรามีหมายเลข N ผู้ขายเค้กคนหนึ่งขายเค้กราคา 40 รูปี และโดนัทที่ราคา 70 รูปีต่อคน เราต้องตรวจสอบว่าเราสามารถซื้อบางส่วนได้ด้วยเงินรูปี N หรือไม่

ดังนั้น หากอินพุตเป็น N =110 เอาต์พุตจะเป็น True เพราะ 40 + 70 =110

เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -

o := false
Define a function dfs(), this will take i,
if i > n, then:
   return false
if i is same as n, then:
   return true
if dfs(i + 40), then:
   return true
return dfs(i + 70)
From the main method, do the following
n := N
o := dfs(0)
return o

ตัวอย่าง

ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -

#include <bits/stdc++.h>
using namespace std;
int n;
bool o = false;

bool dfs(int i) {
   if (i > n)
      return false;
   if (i == n)
      return true;
   if (dfs(i + 40))
      return true;
   return dfs(i + 70);
}
bool solve(int N) {
   n = N;
   o = dfs(0);
   return o;
}
int main(){
   int N = 110;
   cout << solve(N) << endl;
}

อินพุต

110

ผลลัพธ์

1