Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <fstream>
- using namespace std;
- void back(int K, int N, int P, vector<vector<int>> &Sols, int Sol[])
- {
- if (K > P)
- {
- vector<int> v(0);
- for (int i = 1; i <= P; ++i)
- {
- v.push_back(Sol[i]);
- }
- Sols.push_back(v);
- return;
- }
- for (int i = Sol[K - 1] + 1; i <= N; ++i)
- {
- Sol[K] = i;
- back(K + 1, N, P, Sols, Sol);
- }
- }
- void back2(int K, int N, int P, vector<vector<int>> &Sols,
- vector<int> &SolFin, vector<bool> &Fol, int &suma, ofstream &out)
- {
- if (K > P)
- {
- for (int i = 1; i <= P; ++i)
- {
- out << "( ";
- for (int j = 0; j < P; ++j)
- {
- out << Sols[SolFin[i]][j] << ' ';
- }
- out << ")" << endl;
- }
- out << " = " << suma << endl << endl;
- return;
- }
- for (int i = SolFin[K - 1] + 1; i < N; ++i)
- {
- bool continue2 = false;
- int sumaLocal = 0;
- for (int j = 0; j < P; ++j)
- {
- if (Fol[Sols[i][j]])
- {
- for (int k = j - 1; k >= 0; --k)
- {
- Fol[Sols[i][k]] = false;
- }
- continue2 = true;
- break;
- }
- Fol[Sols[i][j]] = true;
- sumaLocal += Sols[i][j];
- }
- if (continue2)
- {
- continue;
- }
- if (K == 1)
- {
- suma = sumaLocal;
- }
- else // if (K > 1)
- {
- if (suma != sumaLocal)
- {
- for (int j = 0; j < P; ++j)
- {
- Fol[Sols[i][j]] = false;
- }
- continue;
- }
- }
- SolFin.push_back(i);
- back2(K + 1, N, P, Sols, SolFin, Fol, suma, out);
- SolFin.pop_back();
- for (int j = 0; j < P; ++j)
- {
- Fol[Sols[i][j]] = false;
- }
- }
- }
- int main()
- {
- int n;
- cout << "n = "; cin >> n;
- ofstream out("iesire.out");
- vector<vector<int>> Sols(0);
- int Sol[100];
- Sol[0] = 0;
- back(1, n * n, n, Sols, Sol);
- vector<int> SolFin(1, -1); // incepand de la indicele propriu 1, contine indici din Sols
- vector<bool> SolFol(Sols.size() + 1, false);
- vector<bool> Fol(n * n + 1, false);
- int suma = 0;
- back2(1, Sols.size(), n, Sols, SolFin, Fol, suma, out);
- out.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement