1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| #include <bits/stdc++.h> #include "longesttrip.h" using namespace std; const int N = 3e2 + 5; int n,D; vector<int> L1,L2; bool are_connected(int x,int y) { vector<int> A(1,x),B(1,y); return are_connected(A,B); } vector<int> longest_trip(int _n,int _d) { n = _n;D = _d;L1.clear();L2.clear(); auto Add2 = [&](const int &C,const int &D) { int A = L1.back(),B = L2.back(); if(are_connected(C,D)) { if(are_connected(A,C)) { L1.push_back(C);L1.push_back(D);return;} if(are_connected(B,C)) { L2.push_back(C);L2.push_back(D);return;} while(L2.size()) L1.push_back(L2.back()),L2.pop_back(); L2.push_back(C);L2.push_back(D);return; } if(are_connected(A,C)) { if(are_connected(B,D)) { L1.push_back(C);L2.push_back(D);return;} L1.push_back(C); while(L2.size()) L1.push_back(L2.back()),L2.pop_back(); L2.push_back(D); return; } if(are_connected(B,C)) { L1.push_back(D);L2.push_back(C); return; } L1.push_back(D); while(L2.size()) L1.push_back(L2.back()),L2.pop_back(); L2.push_back(C); }; for(int i = 0;i < n;i++) { if(L1.empty()) {L1.push_back(i);continue;} if(L2.empty()) {L2.push_back(i);continue;} if(i + 1 < n) { Add2(i,i + 1);++i;continue;} if(are_connected(L1.back(),i)) { L1.push_back(i);continue;} if(are_connected(L2.back(),i)) { L2.push_back(i);continue;} while(L2.size()) L1.push_back(L2.back()),L2.pop_back(); L2.push_back(i); } auto Chk0 = [&]() { if(are_connected(L1.back(),L2.front())) return true; return false; }; auto Mge = [&]() { auto res = L1; for(auto i : L2) res.push_back(i); return res; }; if(Chk0()) return Mge(); reverse(L2.begin(),L2.end()); if(Chk0()) return Mge(); swap(L1,L2); if(Chk0()) return Mge(); reverse(L1.begin(),L1.end()); if(Chk0()) return Mge(); int c1 = 0,c2 = 0; int lef = 0,rig = L1.size(); while(lef < rig) { int mid = lef + rig >> 1; vector<int> pre; for(int i = 0;i <= mid;i++) pre.push_back(L1[i]); if(are_connected(pre,L2)) rig = mid; else lef = mid + 1; } c1 = lef; if(c1 == L1.size()) { return L1.size() > L2.size() ? L1 : L2; } lef = 0,rig = L2.size() - 1; while(lef < rig) { int mid = lef + rig >> 1; vector<int> pre,nd(1,L1[c1]); for(int i = 0;i <= mid;i++) pre.push_back(L2[i]); if(are_connected(pre,nd)) rig = mid; else lef = mid + 1; } c2 = lef; vector<int> res; for(int i = (c1 + 1) % L1.size();i != c1;i = (i + 1) % L1.size()) res.push_back(L1[i]); res.push_back(L1[c1]); res.push_back(L2[c2]); for(int i = (c2 + 1) % L2.size();i != c2;i = (i + 1) % L2.size()) res.push_back(L2[i]); return res; }
|