Matrix


Problem Statement :


The kingdom of Zion has cities connected by bidirectional roads. There is a unique path between any pair of cities. Morpheus has found out that the machines are planning to destroy the whole kingdom. If two machines can join forces, they will attack. Neo has to destroy roads connecting cities with machines in order to stop them from joining forces. There must not be any path connecting two machines.

Each of the roads takes an amount of time to destroy, and only one can be worked on at a time. Given a list of edges and times, determine the minimum time to stop the attack.

For example , there are n = 5   cities called 0 - 4. Three of them have machines and are colored red. The time to destroy is shown next to each road. If we cut the two green roads, there are no paths between any two machines. The time required is 3 + 2 = 5 .


Function Description

Complete the function minTime in the editor below. It must return an integer representing the minimum time to cut off access between the machines.

minTime has the following parameter(s):

roads: a two-dimensional array of integers, each roads[ i ] = [ city1, city, time ]  where cities are connected by a road that takes time to destroy
machines: an array of integers representing cities with machines.



Input Format

The first line of the input contains two space-separated integers, n and  k, the number of cities and the number of machines.

Each of the following n - 1 lines contains three space-separated integers city1 ,  city 2, and time. There is a bidirectional road connecting city1 and city2, and  to destroy this road it takes time units.

Each of the last k lines contains an integer, machine[ i ], the label of a city with a machine.


Constraints

2  <=  n  <=  10^5
2  <=  k  <=  n
1  <=  time[ i ] <=  10^6

Output Format

Return an integer representing the minimum time required to disrupt the connections among all machines.



Solution :



title-img


                            Solution in C :

In   C :






/* Enter your code here. Read input from STDIN. Print output to STDOUT */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 100010

typedef struct edge {
	int a;
	int b;
	int v;
} edge;

edge E[MAX];
int p[MAX];
int b[MAX];

int fun(int x) {
	if ( x == p[x]) {
		return x;
	} else {
		return p[x] = fun(p[x]);
	}
}

int cmp(const void *p, const void *q) {
	const edge * e1 = (const edge *)p;
	const edge * e2 = (const edge *)q;
	return (e1->v > e2->v) ? 0 : 1;
}

int main()
{
	int N, K, i;
	scanf("%d %d", &N, &K);
	for (i = 0; i < N - 1; i++) {
		scanf("%d %d %d", &E[i].a, &E[i].b, &E[i].v);
	}
	qsort(E, N, sizeof(edge), cmp);
	memset(b, 0, sizeof(b));
	for (i = 0; i < K; i++) {
		int idx;
		scanf("%d", &idx);
		b[idx] = 1;
	}

	for(i = 0; i < N; i++) {
		p[i] = i;
	}

	int res = 0;
	for (i = 0; i < N-1; i++) {
		int a = E[i].a;
		int bb = E[i].b;
		int v = E[i].v;

		int pa = fun(a);
		int pb = fun(bb);
		if (!(b[pa] && b[pb])) {
			p[pa] = pb;
			b[pb] |= b[pa];
		} else {
			res += v;
		}
	}
	printf("%d\n", res);
	return 0;
}
                        


                        Solution in C++ :

In   C++  :





#include <cstdio>
#include <vector>

using namespace std;

#define forn(i,n) for (int i = 0; i < (n); i++)
typedef long long LL;
typedef pair<int, int> ii;

#define N 100004
const LL inf = 1000000000000000000LL;
int n, m;
bool marked[N];
LL f[N], g[N];
vector<ii> a[N];

void go(int v, int parent) {
	LL sum = 0, mx = -inf;
	for (vector<ii>::iterator it = a[v].begin(); it != a[v].end(); ++it) {
		int x = it->first;
		if (x == parent) continue;
		go(x, v);
		if (f[x] == inf) continue;
		LL u = min(g[x], f[x] + it->second);
		sum += u;
		mx = max(mx, u - f[x]);
	}
	if (marked[v]) f[v] = sum, g[v] = inf;
		else f[v] = sum - mx, g[v] = sum;
}

int main() {
	scanf("%d%d", &n, &m);
	forn(_, n-1) {
		int x, y, z;
		scanf("%d%d%d", &x, &y, &z);
		a[x].push_back(ii(y, z));
		a[y].push_back(ii(x, z));
	}
	forn(_, m) {
		int x;
		scanf("%d", &x);
		marked[x] = 1;
	}
	go(0, -1);
	printf("%lld\n", min(f[0], g[0]));
	return 0;
}
                    


                        Solution in Java :

In   Java :





import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Scanner;


public class Solution {
	static ArrayList<Edge>[] adj;
	static boolean[] hasX;
	static int N, K;
	static long res = 0;
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);		
		N = sc.nextInt();
		K = sc.nextInt();
		adj = new ArrayList[N];
		hasX = new boolean[N];
		for(int i=0; i<N; i++){
			adj[i] = new ArrayList<Edge>();
		}
		
		for(int i=0; i<N-1; i++){
			int from = sc.nextInt();
			int to = sc.nextInt();
			int weight = sc.nextInt();
			adj[from].add(new Edge(to, weight));
			adj[to].add(new Edge(from, weight));
		}
		
		for(int i=0; i<K; i++){
			hasX[sc.nextInt()] = true;
		}
		sc.close();
		
		res = 0;
		dfs(0, 0, 0);
		System.out.println(res);
	}
	
	static int dfs(int cur, int parent, int parentWeight){
		PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
				
		for(Edge to : adj[cur]){
			if(to.to != parent){
				int cr = dfs(to.to, cur, to.weight);
				if(cr > 0){
					pq.add(cr);
				}
			}
		}
		
		int min = 0;
		while(!pq.isEmpty()){
			res += min;
			min = pq.remove();
		}
		
		if(hasX[cur]){
			res += min;
			return parentWeight;
		} else if(min>0){
			return Math.min(min, parentWeight);
		} else{
			return 0;
		}
	}
	
	static class Edge{
		public int to;
		public int weight;
		
		public Edge(int to, int weight){
			this.to = to;
			this.weight = weight;
		}
	}
}
                    


                        Solution in Python : 
                            
In   Python3 :






def leader(x):
  if P[x]==x:
    return P[x]
  if P[x]==x+10**5:
    return P[x]
  P[x] = leader(P[x])
  return P[x]

def same(x, y):
  return leader(x)==leader(y)

def canJoin(x, y):
  return not(leader(x)>=10**5 and leader(y)>=10**5)

def union(x, y):
  a = leader(x) 
  b = leader(y)
  if a>b:
    a, b = b, a
  S[b]+=S[a]
  P[a] = b


n, k = list(map(int, input().split()))
lis = []
for _ in range(n-1):
  x, y, z = list(map(int, input().split()))
  lis.append((x, y, z))
lis.sort(key=lambda x: -x[2])
P = {x:x for x in range(n)}
S = {x:1 for x in range(n)}
for _ in range(k):
  r = int(input())
  P[r+10**5]=r+10**5
  P[r]=r+10**5
  S[r+10**5]=1
res = 0
for x, y, z in lis:
  if canJoin(x, y):
    union(x, y)
  else:
    res+=z
print(res)
                    


View More Similar Problems

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

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

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →