Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <map>
- #include <set>
- #include <algorithm>
- #include <numeric>
- #include <queue>
- #include <deque>
- #include <random>
- #include <chrono>
- using namespace std;
- typedef long long ll;
- typedef unsigned long long ull;
- typedef long double ld;
- typedef pair<int, int> pii;
- typedef pair<ll, ll> pll;
- #define fast ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
- #define file_in freopen("input.txt", "r", stdin);
- #define all(x) (x).begin(), (x).end()
- #define sz(x) (int)x.size()
- #define fi first
- #define se second
- #define endl '\n'
- template<typename T> istream& operator>>(istream &in, vector<T> &v) { for (auto &el : v) { in >> el; } return in; }
- template<typename T> ostream& operator<<(ostream &out, const vector<T> &v) { for (auto &el : v) { out << el << " "; } return out; }
- template<typename T1, typename T2> istream& operator>>(istream &in, pair<T1, T2> &v) { in >> v.fi >> v.se; return in; }
- template<typename T1, typename T2> ostream& operator<<(ostream &out, const pair<T1, T2> &v) { out << v.fi << " " << v.se; return out; }
- mt19937 rd(chrono::steady_clock::now().time_since_epoch().count());
- void fill(vector<int> &state) {
- iota(all(state), 0);
- shuffle(all(state), rd);
- }
- int get(int i, vector<int> &state) {
- int res = 0;
- for (int j = 0; j < sz(state); ++j) {
- res += abs(i - j) == abs(state[i] - state[j]);
- }
- return res - 1;
- }
- const ll K = (1ll << 32) - 1, LIM = 1000;
- const ld TIME = 0.99, STEP = 0.001;
- ld rnd() { return (ld)rd() / K; }
- ld sigmoid(ld x) { return 1 / (1 + exp(-x)); }
- bool solve(int n, ld start) {
- vector<int> state(n);
- fill(state);
- int cur_cost = 0, same_cost = 0;
- for (int i = 0; i < n; ++i) cur_cost += get(i, state);
- cur_cost >>= 1;
- ld tmp = 2;
- while ((clock() - start) / CLOCKS_PER_SEC <= TIME) {
- tmp -= STEP;
- ++same_cost;
- if (same_cost == LIM || cur_cost == 0) {
- break;
- }
- int i = rd() % n, j = rd() % n;
- int new_cost = cur_cost - get(i, state) - get(j, state);
- swap(state[i], state[j]);
- new_cost += get(i, state) + get(j, state);
- if (cur_cost > new_cost || rnd() < exp((ld)(cur_cost - new_cost) / sigmoid(tmp))) {
- cur_cost = new_cost;
- same_cost = 0;
- } else {
- swap(state[i], state[j]);
- }
- }
- if (cur_cost == 0) {
- for (auto &el : state) cout << el + 1 << ' '; cout << '\n';
- return true;
- } else {
- return false;
- }
- }
- int main() {
- fast
- // file_in
- int n;
- cin >> n;
- ld start = clock();
- while ((clock() - start) / CLOCKS_PER_SEC <= TIME) {
- if (solve(n, start)) {
- break;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement