#include "towns.h"
#include<bits/stdc++.h>
using namespace std;
int f1, f2;
map<pair<int,int>,int> res;
int getDist(int a, int b){
	if (a == b) return 0;
	if (a > b) swap(a, b);
	if (res.find({a, b}) == res.end()) res[{a, b}] = getDistance(a, b);
	return res[{a, b}];
}
int eq(int a, int b){
	return getDist(f1, a)+getDist(f1, b)-getDist(a, b);
}
int hubDistance(int N, int sub){
	res.clear();
	int bsf = 0;
	for (int i=1; i<N; i++){
		int d = getDist(0, i);
		if (d > bsf){
			bsf = d;
			f1 = i;
		}
	}
	bsf = 0;
	for (int i=0; i<N; i++){
		if (i == f1) continue;
		int d = getDist(f1, i);
		if (d > bsf){
			bsf = d;
			f2 = i;
		}
	}
	int diam = getDist(f1, f2);
	map<int,vector<int>> m;
	int R = pow(10, 9);
	for (int i=0; i<N; i++){
		int jp = (getDist(f1, 0)+getDist(f1, i)-getDist(0, i))/2;
		m[jp].push_back(i);
		R = min(R, max(jp, diam-jp));
	}
	int xl = 0, xm, xr = N;
	bool bal = false;
	for (auto [jp, v] : m){
		xr -= v.size();
		xm = v.size();
		if ((jp == R || diam-jp == R) && xl <= N/2 && xr <= N/2){
			if (xm <= N/2) bal = true;
			else {
				vector<bool> in(N, false);
				for (int x : v) in[x] = true;
				vector<int> l, b;
				for (int i=0; i<N; i++){
					if (l.empty()) l.push_back(i);
					else {
						if (in[i] && in[l.back()] && eq(i, l.back()) != 2*jp) b.push_back(i);
						else {
							l.push_back(i);
							if (!b.empty()){
								l.push_back(b.back());
								b.pop_back();
							}
						}
					}
				}
				int t = l.back();
				while (!l.empty()){
					if (in[t] && in[l.back()] && eq(t, l.back()) != 2*jp){
						if (l.size() == 1){
							b.push_back(l.back());
							l.pop_back();
						}
						else {
							l.pop_back();
							l.pop_back();
						}
					}
					else {
						l.pop_back();
						if (b.empty()) break;
						b.pop_back();
					}
				}
				if (b.empty()) bal = true;
			}
		}
		xl += v.size();
	}
	if (bal) return R;
	else return -R;
}
| # | 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... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |