I'm trying to implement a code in c++ that solves the following problem: Given a natural number n, and m pairs of natural numbers between 1 and n, generate (print in the console) all the permutations from 1 to n such that the first element of each pair appears before the second element in the permutation.
The code I've written so far is a simple backtracking algorithm that I have adapted from the standard algorithm for generating all permutations from 1 to n.
In the following code, M is a matrix such that the row M[j] contains all numbers such that j must go before them, and N is a matrix such that N[j] contains all the numbers such that j must go after them. Also, the "used" vector keeps track of the elements that I've already used.
void f(int i){
if (i == n) return print();
if (i == 0){
for (int j = 0; j < n; ++j){
V[i] = j;
used[j] = 1;
f(i+1);
used[j] = 0;
}
}
else {
for (int j = 0; j < n; ++j){
bool aux = true;
int k = 0;
while (aux and k < M[j].size()){
if (used[M[j][k]]) aux = false;
++k;
}
k = 0;
while (aux and k < N[j].size()){
if (not used[N[j][k]]) aux = false;
++k;
}
if (aux){
if (not used[j]){
V[i] = j;
used[j] = 1;
f(i+1);
used[j] = 0;
}
}
}
}
The problem is this code is too slow. So I'm asking you guys if you know any way to make it faster.
What about this?
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <functional>
#include <iterator>
using namespace std;
int main()
{
vector<pair<int,int>> m={{1,2},{4,3}};
vector<int> arr={1,2,3,4,5};
do
{
if (all_of(m.begin(),m.end(),[&](pair<int,int>& p)
{
auto it1 = find(arr.begin(),arr.end(),p.first);
auto it2 = find(arr.begin(),arr.end(),p.second);
return (it1 != arr.end() && it2 != arr.end() && it1 <= it2);
}))
{
for(auto it: arr)
cout<<it<<" ";
cout<<endl;
}
}while(std::next_permutation(arr.begin(),arr.end()));
}