Tree Coordinates


Problem Statement :


We consider metric space to be a pair, , where  is a set and  such that the following conditions hold:

where  is the distance between points  and .

Let's define the product of two metric spaces, , to be  such that:

, where , .
So, it follows logically that  is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: .

For example, , where  is a metric space. , where .

In this challenge, we need a tree-space. You're given a tree, , where  is the set of vertices and  is the set of edges. Let the function  be the distance between two vertices in tree  (i.e.,  is the number of edges on the path between vertices  and ). Note that  is a metric space.

You are given a tree, , with  vertices, as well as  points in . Find and print the distance between the two furthest points in this metric space!

Input Format

The first line contains two space-separated positive integers describing the respective values of  (the number of vertices in ) and  (the number of given points).
Each line  of the  subsequent lines contains two space-separated integers,  and , describing edge  in .
Each line  of the  subsequent lines contains two space-separated integers describing the respective values of  and  for point .

Constraints

Scoring

This challenge uses binary scoring, so you must pass all test cases to earn a positive score.

Output Format

Print a single non-negative integer denoting the maximum distance between two of the given points in metric space .



Solution :


                            Solution in C :

In C ++ :




#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstdlib>
#include <ctime>
#include <deque>
using namespace std;

#define N 200000

int fa[N][21], dep[N], L[N], R[N], Time, n, m;
vector <int> ve[N], ve1[N];
bool used[N];
int zx, sz;
int sum[N], l[N], c[N];
int ans;
int ma1[N], ma2[N], c1[N], c2[N];
int zhan[N], zhan1[N];

void dfs1(int k, int f) {
	fa[k][0] = f;
	dep[k] = dep[f] + 1;
	for (int i = 1; i <= 20; i++)
		fa[k][i] = fa[fa[k][i - 1]][i - 1];
	L[k] = ++Time;
	for (int i = 0; i < (int) ve[k].size(); i++)
		if (ve[k][i] != f)
			dfs1(ve[k][i], k);
	R[k] = Time;
}

void dfs_size(int k) {
	sum[k] = 1;
	used[k] = true;
	for (int i = 0; i < (int) ve[k].size(); i++)
		if (!used[ve[k][i]]) {
			dfs_size(ve[k][i]);
			sum[k] += sum[ve[k][i]];
		}
	used[k] = false;
}

void dfs_zx(int k) {
	// printf("?? %d %d\n", k, sz);
	bool ok = (sz - sum[k] <= sz / 2);
	used[k] = true;
	for (int i = 0; i < (int) ve[k].size(); i++)
		if (!used[ve[k][i]]) {
			if (sum[ve[k][i]] > sz / 2)
				ok = false;
			dfs_zx(ve[k][i]);
		}
	used[k] = false;
	if (ok)
		zx = k;
}

void dfs_l(int k) {
	used[k] = true;
	for (int i = 0; i < (int) ve[k].size(); i++)
		if (!used[ve[k][i]]) {
			l[ve[k][i]] = l[k] + 1;
			dfs_l(ve[k][i]);
		}
	used[k] = false;
}

void dfs_c(int k) {
	used[k] = true;
	for (int i = 0; i < (int) ve[k].size(); i++)
		if (!used[ve[k][i]]) {
			c[ve[k][i]] = c[k];
			dfs_c(ve[k][i]);
		}
	used[k] = false;
}

bool cmp_c(pair<int, int> x, pair<int, int> y) {
	return c[x.first] < c[y.first];
}

bool cmp_L(int x, int y) {
	return L[x] < L[y];
}

int dist(int x, int y) {
	int ans = 0;
	if (dep[x] < dep[y])
		swap(x, y);
	for (int i = 20; i >= 0; i--)
		if (dep[fa[x][i]] >= dep[y])
			ans += (1 << i), x = fa[x][i];
	if (x == y)
		return ans;
	for (int i = 20; i >= 0; i--)
		if (fa[x][i] != fa[y][i])
			ans += 1 << (i + 1), x = fa[x][i], y = fa[y][i];
	return ans + 2;
}

int lca(int x, int y) {
	int ans = 0;
	if (dep[x] < dep[y])
		swap(x, y);
	for (int i = 20; i >= 0; i--)
		if (dep[fa[x][i]] >= dep[y])
			ans += (1 << i), x = fa[x][i];
	if (x == y)
		return x;
	for (int i = 20; i >= 0; i--)
		if (fa[x][i] != fa[y][i])
			ans += 1 << (i + 1), x = fa[x][i], y = fa[y][i];
	return fa[x][0];
}

void dfs_d(int k) {
	// ma1[k] = -1000000000;
	// ma2[k] = -1000000000;
	// ma1[k] = v[k];
	// c1[k] = c[k];
	// printf("?? %d\n", k);
	for (int i = 0; i < (int) ve1[k].size(); i++) {
		int t = ve1[k][i];
		dfs_d(t);
		ma1[t] += dep[t] - dep[k];
		ma2[t] += dep[t] - dep[k];
		if (c1[k] != c1[t] || !c1[k] || !c1[t])
			ans = max(ans, ma1[k] + ma1[t]);
		if (c1[k] != c2[t] || !c1[k] || !c2[t])
			ans = max(ans, ma1[k] + ma2[t]);

		if (c2[k] != c1[t] || !c2[k] || !c1[t])
			ans = max(ans, ma2[k] + ma1[t]);

		if (c2[k] != c2[t] || !c2[k] || !c2[t])
			ans = max(ans, ma2[k] + ma2[t]);
		
		if (ma1[t] > ma1[k]) {
			if (c1[t] == c1[k])
				ma1[k] = ma1[t];
			else {
				ma2[k] = ma1[k];
				c2[k] = c1[k];
				ma1[k] = ma1[t];
				c1[k] = c1[t];
			}
		}else if (ma1[t] > ma2[k] && c1[t] != c1[k]) {
			ma2[k] = ma1[t];
			c2[k] = c1[t];
		}
		if (ma2[t] > ma1[k]) {
			if (c2[t] == c1[k])
				ma1[k] = ma2[t];
			else {
				ma2[k] = ma1[k];
				c2[k] = c1[k];
				ma1[k] = ma2[t];
				c1[k] = c2[t];
			}
		}else if (ma2[t] > ma2[k] && c2[t] != c1[k]) {
			ma2[k] = ma2[t];
			c2[k] = c2[t];
		}

	}
}

void doit(vector <pair<int, int> > V) {
	int len = 0;
	// printf("%d\n", ans);
	for (int i = 0; i < (int) V.size(); i++) {
		zhan[++len] = V[i].second;


		if (c[V[i].first] != c1[V[i].second] || !c[V[i].first] || !c1[V[i].second]) {
			ans = max(ans, ma1[V[i].second] + l[V[i].first]);
		}
		if (c[V[i].first] != c2[V[i].second] || !c[V[i].first] || !c2[V[i].second]) {
			ans = max(ans, ma2[V[i].second] + l[V[i].first]);
		}
		
		if (l[V[i].first] > ma1[V[i].second]) {
			if (c[V[i].first] != c1[V[i].second]) {
				ma2[V[i].second] = ma1[V[i].second];
				c2[V[i].second] = c1[V[i].second];
				ma1[V[i].second] = l[V[i].first];
				c1[V[i].second] = c[V[i].first];
			}else {
				ma1[V[i].second] = l[V[i].first];
			}
		}else if (l[V[i].first] > ma2[V[i].second] && c[V[i].first] != c1[V[i].second]) {
			ma2[V[i].second] = l[V[i].first];
			c2[V[i].second] = c[V[i].first];
		}

	}
	// printf("%d\n", ans);
	sort(zhan + 1, zhan + len + 1, cmp_L);

	for (int i = len; i > 1; i--) {
		zhan[++len] = lca(zhan[i - 1], zhan[i]);
	}
	sort(zhan + 1, zhan + len + 1, cmp_L);

	for (int i = 1; i < len; i++) {
		ve1[zhan[i]].clear();
	}
	// for (int i = 1; i <= len; i++)
	// 	printf("%d ", zhan[i]);
	// printf("\n");
	int len1 = 0;
	zhan1[len1 = 1] = zhan[1];
	for (int i = 2; i <= len; i++)
		if (zhan[i] != zhan[i - 1]) {
			while (len1 > 0 && R[zhan1[len1]] < L[zhan[i]])
				len1 --;
			zhan1[++len1] = zhan[i];
			ve1[zhan1[len1 - 1]].push_back(zhan1[len1]);
		}
	dfs_d(zhan[1]);
	// for (int i = 0; i < (int) V.size(); i++)
	// 	for (int j = 0; j < i; j++)
	// 		if (c[V[i].first] != c[V[j].first] || !c[V[i].first] || !c[V[j].first]) {
	// 			// printf("xx %d %d\n", l[V[i].first] + l[V[j].first], dist(V[i].second, V[j].second));
	// 			ans = max(ans, l[V[i].first] + l[V[j].first] + dist(V[i].second, V[j].second));
	// 		}
	for (int i = 1; i <= len; i++) {
		// v[V[i].second] = -1000000000;
		ma1[zhan[i]] = ma2[zhan[i]] = -1000000000;
	}
}

void doit1(vector <pair<int, int> > V) {
	for (int i = 0; i < (int) V.size(); i++)
		for (int j = 0; j < i; j++)
			// if (c[V[i].first] != c[V[j].first] || !c[V[i].first] || !c[V[j].first]) {
				// printf("xx %d %d\n", l[V[i].first] + l[V[j].first], dist(V[i].second, V[j].second));
				ans = max(ans, dist(V[i].first, V[j].first) + dist(V[i].second, V[j].second));
			// }
}

void dfs(int k, vector <pair<int, int> > V) {
	// printf("?? %d\n", k);
	if (V.size() <= 1)
		return ;
	if (V.size() <= 100) {
		doit1(V);
		return ;
	}
	dfs_size(k);
	sz = sum[k];
	dfs_zx(k);
	k = zx;
	l[k] = 0;
	dfs_l(k);
	c[k] = 0;
	used[k] = true;
	int tot = 0;
	for (int i = 0; i < (int) ve[k].size(); i++)
		if (!used[ve[k][i]]) {
			tot += 1;
			c[ve[k][i]] = tot;
			dfs_c(ve[k][i]);
		}
	used[k] = false;

	
	doit(V);


	sort(V.begin(), V.end(), cmp_c);
	int q = 0;
	used[k] = true;
	vector <int> vv;
	for (int i = 0; i <= tot; i++) {
		while (q < (int) V.size() && c[V[q].first] <= i)
			q += 1;
		vv.push_back(q);
	}
	tot = 0;
	for (int i = 0; i < (int) ve[k].size(); i++)
		if (!used[ve[k][i]]) {
			tot += 1;
			vector <pair<int, int> > V1;
			// printf("?? %d %d %u\n", vv[tot - 1], vv[tot], V.size());
			for (int j = vv[tot - 1]; j < vv[tot]; j++)
				V1.push_back(V[j]);
			dfs(ve[k][i], V1);
		}
	used[k] = false;
}

int main() {
	scanf("%d%d", &n, &m);
	for (int i = 1; i < n; i++) {
		int x, y;
		scanf("%d%d", &x, &y);
		// x = i;
		// y = i + 1;
		ve[x].push_back(y);
		ve[y].push_back(x);
	}
	vector <pair<int, int> > V;
	for (int i = 1; i <= m; i++) {
		int x, y;
		scanf("%d%d", &x, &y);
		V.push_back(make_pair(x, y));
	}
	dfs1(1, 0);
	for (int i = 1; i <= n; i++)
		ma1[i] = ma2[i] = -1000000000;
	dfs(1, V);
	printf("%d\n", ans);
}







In Java :





import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;

public class Solution {

    static class Reader 
    { 
        final private int BUFFER_SIZE = 1 << 16; 
        private DataInputStream din; 
        private byte[] buffer; 
        private int bufferPointer, bytesRead; 
  
        public Reader() 
        { 
            din = new DataInputStream(System.in); 
            buffer = new byte[BUFFER_SIZE]; 
            bufferPointer = bytesRead = 0; 
        } 
  
        public Reader(String file_name) throws IOException 
        { 
            din = new DataInputStream(new FileInputStream(file_name)); 
            buffer = new byte[BUFFER_SIZE]; 
            bufferPointer = bytesRead = 0; 
        } 
  
        public String readLine() throws IOException 
        { 
            byte[] buf = new byte[64]; // line length 
            int cnt = 0, c; 
            while ((c = read()) != -1) 
            { 
                if (c == '\n') 
                    break; 
                buf[cnt++] = (byte) c; 
            } 
            return new String(buf, 0, cnt); 
        } 
  
        public int nextInt() throws IOException 
        { 
            int ret = 0; 
            byte c = read(); 
            while (c <= ' ') 
                c = read(); 
            boolean neg = (c == '-'); 
            if (neg) 
                c = read(); 
            do
            { 
                ret = ret * 10 + c - '0'; 
            }  while ((c = read()) >= '0' && c <= '9'); 
  
            if (neg) 
                return -ret; 
            return ret; 
        } 
  
        public long nextLong() throws IOException 
        { 
            long ret = 0; 
            byte c = read(); 
            while (c <= ' ') 
                c = read(); 
            boolean neg = (c == '-'); 
            if (neg) 
                c = read(); 
            do { 
                ret = ret * 10 + c - '0'; 
            } 
            while ((c = read()) >= '0' && c <= '9'); 
            if (neg) 
                return -ret; 
            return ret; 
        } 
  
        public double nextDouble() throws IOException 
        { 
            double ret = 0, div = 1; 
            byte c = read(); 
            while (c <= ' ') 
                c = read(); 
            boolean neg = (c == '-'); 
            if (neg) 
                c = read(); 
  
            do { 
                ret = ret * 10 + c - '0'; 
            } 
            while ((c = read()) >= '0' && c <= '9'); 
  
            if (c == '.') 
            { 
                while ((c = read()) >= '0' && c <= '9') 
                { 
                    ret += (c - '0') / (div *= 10); 
                } 
            } 
  
            if (neg) 
                return -ret; 
            return ret; 
        } 
  
        private void fillBuffer() throws IOException 
        { 
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); 
            if (bytesRead == -1) 
                buffer[0] = -1; 
        } 
  
        private byte read() throws IOException 
        { 
            if (bufferPointer == bytesRead) 
                fillBuffer(); 
            return buffer[bufferPointer++]; 
        } 
  
        public void close() throws IOException 
        { 
            if (din == null) 
                return; 
            din.close(); 
        } 
    } 
    
    static int[][] buildSparseTable(int[] arr) {
        int pow = 1;
        while ((1 << pow) < arr.length) pow++;
        int[][] result = new int[arr.length][pow];
        for (int i = 0; i < arr.length; i++) result[i][0] = arr[i];
        for (int j = 1; j <= pow; j++) {
            for (int i = 0; i + (1 << j) <= arr.length; i++) {
                result[i][j] = Math.min(result[i][j-1],
                                        result[i + (1 << (j-1))][j-1]);
            }
        }
        return result;
    }

    /*
     * Complete the treeCoordinates function below.
     */
    static int treeCoordinates(int n, int[][] edges, int[][] points) {
        ArrayList<Integer>[] nodes = new ArrayList[n + 1];
        for (int i = 1; i <= n; i++) nodes[i] = new ArrayList<Integer>();
        for (int[] edge : edges) {
            nodes[edge[0]].add(edge[1]);
            nodes[edge[1]].add(edge[0]);
        }

        // Find diameter (two BFS)
        int root = 0;
        int tail = 0;
        {
            class Entry {
                int node;
                int dist;
                public Entry(int node, int dist) {
                    this.node = node;
                    this.dist = dist;
                }
            }
            LinkedList<Entry> Q = new LinkedList<Entry>();
            boolean[] visited = new boolean[n + 1];
            visited[1] = true;
            Q.offer(new Entry(1, 0));
            int maxDist = 0;
            int farNode = 1;
            while (Q.size() > 0) {
                Entry cur = Q.poll();
                if (cur.dist > maxDist) {
                    maxDist = cur.dist;
                    farNode = cur.node;
                }
                for (int neighbor : nodes[cur.node]) {
                    if (visited[neighbor]) continue;
                    visited[neighbor] = true;
                    Q.offer(new Entry(neighbor, cur.dist + 1));
                }
            }
            root = farNode;
            
            Q = new LinkedList<Entry>();
            visited = new boolean[n + 1];
            visited[root] = true;
            Q.offer(new Entry(root, 0));
            maxDist = 0;
            farNode = root;
            while (Q.size() > 0) {
                Entry cur = Q.poll();
                if (cur.dist > maxDist) {
                    maxDist = cur.dist;
                    farNode = cur.node;
                }
                for (int neighbor : nodes[cur.node]) {
                    if (visited[neighbor]) continue;
                    visited[neighbor] = true;
                    Q.offer(new Entry(neighbor, cur.dist + 1));
                }
            }
            tail = farNode;
        }
        //System.out.println("root = " + root + ", tail = " + tail);

        // Euler tour
        int[] eulerTour = new int[2*n - 1];
        final int[] depth = new int[n + 1];
        int[] eulerLevels = new int[2*n - 1];
        int[] eulerIndex = new int[n + 1];
        boolean[] visited = new boolean[n + 1];
        
        int[] S = new int[n];
        int spos = 0;
        S[0] = root;
        int pos = 0;
        int[] neighborCount = new int[n + 1];
        while (spos > -1) {
            int cur = S[spos--];
            if (!visited[cur]) {
                depth[cur] = spos + 1;
                eulerIndex[cur] = pos;
                visited[cur] = true;
            }
            eulerLevels[pos] = spos + 1;
            eulerTour[pos] = cur;
            pos++;
            while (neighborCount[cur] < nodes[cur].size()) {
                if (visited[nodes[cur].get(neighborCount[cur])]) {
                    neighborCount[cur]++;
                    continue;
                }
                int next = nodes[cur].get(neighborCount[cur]);
                //parent[next] = cur;
                S[++spos] = cur;
                S[++spos] = next;
                neighborCount[cur]++;
                break;
            }
        }
        //System.out.println(Arrays.toString(eulerTour));
        //System.out.println(Arrays.toString(eulerLevels));
        //System.out.println(Arrays.toString(eulerIndex));

        // Sparse table
        int[][] lookup = buildSparseTable(eulerLevels);
        //for (int i = 0; i < lookup.length; i++) {
        //    for (int j = 0; j < lookup[0].length; j++) {
        //        System.out.print(lookup[i][j] + " ");
        //    }
        //    System.out.println();
        //}

        class Entry implements Comparable<Entry> {
            int x;
            int y;
            int val;
            public Entry(int x, int y, int val) {
                this.x = x;
                this.y = y;
                this.val = val;
            }
            public int compareTo(Entry other) {
                return val - other.val;
            }
        }
        List<Entry> list1 = new ArrayList<Entry>(points.length);
        List<Entry> list2 = new ArrayList<Entry>(points.length);
        List<Entry> list3 = new ArrayList<Entry>(points.length);
        List<Entry> list4 = new ArrayList<Entry>(points.length);

        for (int i = 0; i < points.length; i++) {
            int x = points[i][0];
            int y = points[i][1];
            int xLcaLevel;
            {
                int start = Math.min(eulerIndex[x], eulerIndex[tail]);
                int end = Math.max(eulerIndex[x], eulerIndex[tail]);
                int pow = 0;
                while (1 << (pow + 1) <= (end - start)) pow++;
                xLcaLevel = Math.min(lookup[start][pow],   
                                     lookup[end + 1 - (1<<pow)][pow]);
            }
            int yLcaLevel;
            {
                int start = Math.min(eulerIndex[y], eulerIndex[tail]);
                int end = Math.max(eulerIndex[y], eulerIndex[tail]);
                int pow = 0;
                while (1 << (pow + 1) <= (end - start)) pow++;
                yLcaLevel = Math.min(lookup[start][pow],   
                                     lookup[end + 1 - (1<<pow)][pow]);
            }
            int val1 = depth[x] + depth[y];
            list1.add(new Entry(x, y, val1));
            int val2 = -depth[x] - depth[y] + 2*xLcaLevel + 2*yLcaLevel;
            list2.add(new Entry(x, y, val2));
            int val3 = depth[x] + depth[y] - 2*xLcaLevel;
            list3.add(new Entry(x, y, val3));
            int val4 = -depth[x] - depth[y] + 2*yLcaLevel;
            list4.add(new Entry(x, y, val4));
        }
        Collections.sort(list1, Collections.reverseOrder());
        Collections.sort(list2);
        Collections.sort(list3, Collections.reverseOrder());
        Collections.sort(list4);

        //int maxDist = Math.max(list1.get(0).val - list2.get(0).val, list3.get(0).val - list4.get(0).val);
        int maxDist = 0;

        for (int i = 0; i < points.length; i++) {
            // ith increasing diagonal
            boolean shouldContinue = false;
            for (int j = 0; j <= i; j++) {
                Entry e1 = list1.get(i-j);
                Entry e2 = list2.get(j);
                int potential12 = e1.val - e2.val;
                if (potential12 > maxDist) {
                    shouldContinue = true;
                    int x1 = e1.x;
                    int y1 = e1.y;
                    int x2 = e2.x;
                    int y2 = e2.y;
                    int xLcaLevel;
                    {
                        int start = Math.min(eulerIndex[x1], eulerIndex[x2]);
                        int end = Math.max(eulerIndex[x1], eulerIndex[x2]);
                        int pow = 0;
                        while (1 << (pow + 1) <= (end - start)) pow++;
                        xLcaLevel = Math.min(lookup[start][pow],   
                                             lookup[end + 1 - (1<<pow)][pow]);
                    }
                    int yLcaLevel;
                    {
                        int start = Math.min(eulerIndex[y1], eulerIndex[y2]);
                        int end = Math.max(eulerIndex[y1], eulerIndex[y2]);
                        int pow = 0;
                        while (1 << (pow + 1) <= (end - start)) pow++;
                        yLcaLevel = Math.min(lookup[start][pow],   
                                             lookup[end + 1 - (1<<pow)][pow]);
                    }
                    int actual12 = depth[x1] + depth[x2] - 2*xLcaLevel
                                   + depth[y1] + depth[y2] - 2*yLcaLevel;
                    maxDist = Math.max(maxDist, actual12);
                }
                Entry e3 = list3.get(i-j);
                Entry e4 = list4.get(j);
                int potential34 = e3.val - e4.val;
                if (potential34 > maxDist) {
                    shouldContinue = true;
                    int x3 = e3.x;
                    int y3 = e3.y;
                    int x4 = e4.x;
                    int y4 = e4.y;
                    int xLcaLevel;
                    {
                        int start = Math.min(eulerIndex[x3], eulerIndex[x4]);
                        int end = Math.max(eulerIndex[x3], eulerIndex[x4]);
                        int pow = 0;
                        while (1 << (pow + 1) <= (end - start)) pow++;
                        xLcaLevel = Math.min(lookup[start][pow],   
                                             lookup[end + 1 - (1<<pow)][pow]);
                    }
                    int yLcaLevel;
                    {
                        int start = Math.min(eulerIndex[y3], eulerIndex[y4]);
                        int end = Math.max(eulerIndex[y3], eulerIndex[y4]);
                        int pow = 0;
                        while (1 << (pow + 1) <= (end - start)) pow++;
                        yLcaLevel = Math.min(lookup[start][pow],   
                                             lookup[end + 1 - (1<<pow)][pow]);
                    }
                    int actual34 = depth[x3] + depth[x4] - 2*xLcaLevel
                                   + depth[y3] + depth[y4] - 2*yLcaLevel;
                    maxDist = Math.max(maxDist, actual34);
                }
            }
            if (!shouldContinue) break;
        }

        return maxDist;
    }

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
        Reader reader = new Reader();

        int n = reader.nextInt();
        int m = reader.nextInt();

        int[][] edges = new int[n-1][2];

        for (int edgesRowItr = 0; edgesRowItr < n-1; edgesRowItr++) {
            edges[edgesRowItr][0] = reader.nextInt();
            edges[edgesRowItr][1] = reader.nextInt();
        }

        int[][] points = new int[m][2];

        for (int pointsRowItr = 0; pointsRowItr < m; pointsRowItr++) {
            points[pointsRowItr][0] = reader.nextInt();
            points[pointsRowItr][1] = reader.nextInt();
        }

        int result = treeCoordinates(n, edges, points);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedWriter.close();
    }
}







In Python3 :



#!/bin/python3

import sys


n,m = input().strip().split(' ')
n,m = [int(n),int(m)]
edges = []
for edges_i in range(n-1):
   edges_t = [int(edges_temp) for edges_temp in input().strip().split(' ')]
   edges.append(edges_t)
points = []
for points_i in range(m):
   points_t = [int(points_temp) for points_temp in input().strip().split(' ')]
   points.append(points_t)
# your code goes here
    
class Node:
    def __init__(self,i):
        self.id = i
        self.neighbors = set()

nodes = [Node(i) for i in range(n)]
for from_id,to_id in edges:
    nodes[from_id-1].neighbors.add(nodes[to_id-1])
    nodes[to_id-1].neighbors.add(nodes[from_id-1])

distances = [[10**5] * n for _ in range(n)]
for i in range(n):
    distances[i][i] = 0
    
def set_distance(i, j, new_dist):
    distances[i][j] = new_dist
    distances[j][i] = new_dist
     
# find pair-wise distances with bfs <-- O(n^2)
for center_node in nodes:
    cur_dist = 1
    marked = set([center_node])
    cur_level = set([center_node])
    while cur_level:
        next_level = set()
        for node in cur_level:
            for neighbor in node.neighbors:
                if not neighbor in marked:
                    marked.add(neighbor)
                    next_level.add(neighbor)
                    set_distance(center_node.id, neighbor.id, cur_dist)
        cur_level = next_level
        cur_dist += 1

# now go through the points
max_dist = 0
for p1 in range(m):
    x1, y1 = points[p1]
    x1 -= 1
    y1 -= 1
    for p2 in range(p1 + 1, m):
        x2, y2 = points[p2]
        x2 -= 1
        y2 -= 1
        new_dist = distances[x1][x2] + distances[y1][y2]
        if new_dist > max_dist:
            max_dist = new_dist

print(max_dist)
                        




View More Similar Problems

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →