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 :

```                            ```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 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();
}

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){
}
}
}

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 :

if P[x]==x:
return P[x]
if P[x]==x+10**5:
return P[x]
return P[x]

def same(x, y):

def canJoin(x, y):

def union(x, 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)```
```

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do