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);
map<pair<int, int>, bool> cache;
bool qry(int a, int b){
if(a > b) swap(a, b);
auto p = make_pair(a, b);
if(cache.count(p)) return cache[p];
else return cache[p] = are_connected({a}, {b});
}
vector<int> longest_trip(int N, int D){
cache.clear();
(void)D;
vector<int> ord(N);
for(int i = 0; i < N; i++) ord[i] = i;
shuffle(ord.begin(), ord.end(), rng);
vector<vector<int>> paths{{ord[0]}, {ord[1]}};
for(int k = 2; k < N; k++){
int i = ord[k];
int j = rng() % 2;
if(rng() % 2){
if(qry(paths[0].back(), paths[1].back())){
paths[0].insert(paths[0].end(), paths[1].rbegin(), paths[1].rend());
paths[1] = {i};
}
else if(qry(paths[j].back(), i)) paths[j].push_back(i);
else paths[j^1].push_back(i);
}
else{
if(qry(paths[j].back(), i)) paths[j].push_back(i);
else if(qry(paths[0].back(), paths[1].back())){
paths[0].insert(paths[0].end(), paths[1].rbegin(), paths[1].rend());
paths[1] = {i};
}
else paths[j^1].push_back(i);
}
}
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(!qry(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... |