This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#include "longesttrip.h"
using namespace std;
#define sz(x) (int)(x.size())
mt19937 rng(42);
vector<int> longest_trip(int N, int D){
(void)D;
vector<vector<int>> paths;
for(int i = 0; i < N; i++) paths.push_back({i});
auto doMerge = [&](int a, int b){
if(a > b) swap(a, b);
vector<int> va = paths[a], vb = paths[b];
paths.erase(paths.begin()+b);
paths.erase(paths.begin()+a);
reverse(va.begin(), va.end());
va.insert(va.end(), vb.begin(), vb.end());
paths.push_back(va);
};
while(sz(paths) >= 3){
vector<int> ord = {0, 1, 2};
shuffle(ord.begin(), ord.end(), rng);
if(are_connected({paths[ord[0]][0]}, {paths[ord[1]][0]})){
doMerge(ord[0], ord[1]);
}
else if(are_connected({paths[ord[0]][0]}, {paths[ord[2]][0]})){
doMerge(ord[0], ord[2]);
}
else doMerge(ord[1], ord[2]);
}
if(sz(paths) == 1) return paths[0];
if(!are_connected(paths[0], paths[1])){
return sz(paths[0]) > sz(paths[1]) ? paths[0] : paths[1];
}
for(int i = 0; i < 2; i++){
if(sz(paths[i]) < 3) continue;
if(!are_connected({paths[i][0]}, {paths[i].back()})){
if(are_connected({paths[i][0]}, {paths[i^1][0]})){
reverse(paths[i].begin(), paths[i].end());
}
paths[i].insert(paths[i].end(), paths[i^1].begin(), paths[i^1].end());
return paths[i];
}
}
auto prefix = [&](vector<int> v, int len){
vector<int> w;
for(int i = 0; i <= len; i++) w.push_back(v[i]);
return w;
};
int lo = 0, hi = sz(paths[0])-1;
while(lo < hi){
int m = (lo+hi)/2;
if(are_connected(prefix(paths[0], m), paths[1])) hi = m;
else lo = m+1;
}
int p1 = lo;
lo = 0, hi = sz(paths[1])-1;
while(lo < hi){
int m = (lo+hi)/2;
if(are_connected(prefix(paths[0], p1), prefix(paths[1], m))) hi = m;
else lo = m+1;
}
vector<int> res;
for(int i = 1; i <= sz(paths[0]); i++){
res.push_back(paths[0][(p1+i)%sz(paths[0])]);
}
for(int i = 0; i < sz(paths[1]); i++){
res.push_back(paths[1][(lo+i)%sz(paths[1])]);
}
return res;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |