Advertisement
hoanmalai

Plus Equation

Jan 2nd, 2023
854
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. string answer = "";
  6. string s;
  7. int target;
  8.  
  9. void backtracking(int index, string &curAns, int curNum, int curSum) {
  10.   if (!answer.empty())
  11.     return;
  12.   if (index == s.size()) {
  13.     curSum += curNum;
  14.     if (curSum == target) {
  15.       answer = curAns;
  16.     }
  17.     return;
  18.   }
  19.   // Đặt dấu + trước vị trí hiện tại
  20.   if (index) {
  21.     string newAns = curAns + "+" + s[index];
  22.     int newNum = s[index] - '0';
  23.     int newSum = curSum + curNum;
  24.     backtracking(index + 1, newAns, newNum, newSum);
  25.   }
  26.   string newAns = curAns + s[index];
  27.   int newNum = curNum * 10 + s[index] - '0';
  28.   int newSum = curSum;
  29.   // Không đặt dấu +
  30.   backtracking(index + 1, newAns, newNum, newSum);
  31.  
  32. }
  33.  
  34. void backtrack(int index, string &curAns, int curSum) {
  35.   if (!answer.empty())
  36.     return;
  37.   if (index == s.size()) {
  38.     if (curSum == target) {
  39.       answer = curAns;
  40.     }
  41.     return;
  42.   }
  43.   // | 154+89001
  44.   string newAns = curAns;
  45.   if (index != 0) newAns += "+";
  46.   newAns += s[index];
  47.   int curNum = s[index] - '0';
  48.   for (int i = index + 1; i <= s.size(); i++) {
  49.     backtrack(i, newAns, curSum + curNum);
  50.     curNum = curNum * 10 + s[i] - '0';
  51.     newAns += s[i];
  52.   }
  53.   backtrack(s.size(), newAns, curSum + curNum);
  54. }
  55.  
  56. int main() {
  57.   int T;
  58.   cin >> T;
  59.   while (T--) {
  60.     cin >> s >> target;
  61.     string curAns = "";
  62.     answer = "";
  63.     // backtracking(0, curAns, 0, 0);
  64.     backtrack(0, curAns, 0);
  65.     cout << answer << endl;
  66.   }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement