Code:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <cstring>
#include <queue>
using namespace std;
int from, to;
vector<int>niz;
map <int, int> prim;
bool isPrim( int n ) {
int i=2;
while (i<=sqrt(n)){
if (!(n%i)) return false;
if (i==2) --i;
i+=2;
}
return true;
}
void trace(vector<int> a){
for (int i=0; i<a.size(); ++i){
cout << a[i] << " ";
}
cout << endl;
}
bool isValid (vector<int> o){
int i=0;
while ( i<o.size()){
if (i) if (isPrim(o[i]+o[i-1])) {
while (true){
int done=0;
int j=i;
while (j<o.size()) {
if (niz[j]==o[i]+1) swap(niz[j], niz[i]), sort (niz.begin()+j, niz.end()), done=1;
j++;
}
if (done || !i) break;
else --i;
}
return 0;
}
++i;
}
return 1;
}
int main (){
cin >> from >> to;
to++;
niz.resize(to-from);
for (int i=0; i<to-from;++i){
niz[i]=i+from;
}
while (true){
if (!next_permutation(niz.begin(), niz.end())) {cout << 0; system("pause"); return 0;}
else if (isValid(niz)) break;
}
for (int i=0; i<to-from;++i){
cout << niz[i];
if (i!=to-from-1) cout << endl;
}
system("PAUSE");
return 0;
}
This code works but it's not fast enough to pass all the tests, it passes 12/20.
Do you have any ideas how to optimize it more?
You should look for a transposition that yields the greatest reduction in this error function.
I don't think this code uses that method but that's the problem, how to I cycle trough the transpositions?