0% found this document useful (0 votes)
2 views4 pages

Back Tracking

The document contains two C++ programs. The first program implements a backtracking algorithm to find ways to partition an array into two subsets with equal sums, while the second program navigates a grid to find the lexicographically smallest binary number formed by the path from the top-left to the bottom-right corner. Both programs utilize recursive functions and handle input and output accordingly.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Back Tracking

The document contains two C++ programs. The first program implements a backtracking algorithm to find ways to partition an array into two subsets with equal sums, while the second program navigates a grid to find the lexicographically smallest binary number formed by the path from the top-left to the bottom-right corner. Both programs utilize recursive functions and handle input and output accordingly.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

TIENTE

#include<bits/stdc++.h>
using namespace std;
int n;
vector<int> a;
vector<char> sol;
vector<vector<char> > kq;
void BackTracking(int k, vector<int> a, vector<char> sol){
if (k==n) {
int sa=0, sb=0;
for (int i=0;i<sol.size();i++) {
if (sol[i]=='A') sa+=a[i];
else sb+=a[i];
}
if (sa==sb) {
kq.push_back(sol);
}
return;
}
for (char c:{'A','B'}) {
sol.push_back(c);
BackTracking(k+1, a, sol);
sol.pop_back();
}
}
signed main()
{
int test = 0;
cin >> n;
for (int i=0;i<n;i++) {
int x;
cin >> x;
a.push_back(x);
test += x;
}
if (test%2!=0) {
cout << "khong chia duoc";
return 0;
}
BackTracking(0, a, sol);
if (kq.size()==0) cout << "khong chia duoc";
else {
cout << kq.size() << "\n";
for (vector<char> i:kq) {
for (char j:i) cout << j << " ";
cout << "\n";
}
}
}
ROBOT2
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n, dy[2]={0,1}, dx[2]={1,0};
vector<vector<int> > a;
string s, maxx="1111111111111111111";
ll chuyen(string s){
ll chuyen=0, d=0;
for (int i=s.size()-1;i>=0;i--) {
ll res=s[i]-48;
chuyen+=res*pow(2, d++);
}
return chuyen;
}
void Try(ll x, ll y) {
if (x==n-1 && y==n-1) {
if (maxx>s) maxx=s;
return;
}
else {
for (int i=0;i<2;i++) {
int xx=x+dx[i];
int yy=y+dy[i];
if (xx<n && yy<n && a[xx][yy]!=-1) {
s+=(a[xx][yy]+'0');
Try(xx,yy);
s.erase(s.length()-1,1);
}
}
}
}
signed main()
{
cin >> n;
for (int i=0;i<n;i++) {
vector<int> row;
for (int j=0;j<n;j++) {
int x;
cin >> x;
row.push_back(x);
}
a.push_back(row);
}
s+=(a[0][0]+'0');
Try(0,0);
cout << chuyen(maxx);
}

You might also like