สมมติว่าเรามีฟังก์ชัน f ที่รับพารามิเตอร์สองตัว (x, y) เราต้องคืนค่า x และ y ทุกคู่ โดยที่ f(x, y) =z z ถูกกำหนดเป็นอินพุต และ x, y เป็นจำนวนเต็มบวก ฟังก์ชั่นที่เพิ่มขึ้นอย่างต่อเนื่อง ดังนั้น f(x, y)
เพื่อแก้ปัญหานี้ เราจะดำเนินการอย่างตรงไปตรงมา รับ i ในช่วง 1 ถึง 1000 และ j ในช่วง 1 ถึง 1000 สำหรับชุดค่าผสมทั้งหมดของ i,j ถ้า f(i, j) =0 ให้คืนค่าจริง ไม่เช่นนั้นจะเป็นเท็จ
พิจารณารหัสฟังก์ชัน (ควรระบุ) คือ 1 สำหรับการบวก 2 สำหรับการคูณ นอกจากนี้ยังใช้ค่า z ด้วย
ตัวอย่าง
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
#include <bits/stdc++.h> using namespace std; void print_vector(vector<vector<int> > v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << "["; for(int j = 0; j <v[i].size(); j++){ cout << v[i][j] << ", "; } cout << "],"; } cout << "]"<<endl; } class CustomFunction { int id; public: CustomFunction(int id){ this->id = id; } int f(int x, int y){ if(id == 1) return y + x; else if(id == 2) return y * x; return 0; } }; class Solution { public: vector<vector<int>> findSolution(CustomFunction& c, int z) { vector < vector <int > > ans; for(int i = 1; i <= 1000; i++ ){ for(int j = 1; j <= 1000; j++){ if(c.f(i,j) == z){ vector <int> t; t.push_back(i); t.push_back(j); ans.push_back(t); } } } return ans; } }; main(){ Solution ob; CustomFunction c(1); print_vector(ob.findSolution(c, 7)); }
อินพุต
1 7
ผลลัพธ์
[[1, 6, ],[2, 5, ],[3, 4, ],[4, 3, ],[5, 2, ],[6, 1, ],]