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 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
Waiter
You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the
View Solution →Queue using Two Stacks
A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que
View Solution →Castle on the Grid
You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):
View Solution →Down to Zero II
You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.
View Solution →Truck Tour
Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr
View Solution →Queries with Fixed Length
Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon
View Solution →