Arpa's weak amphitheater and Mehrdad's valuable Hoses (Codeforces 742D)
Tags: DP, dsu

Just to remind, girls in Arpa's land are really nice.Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≤ i < k, and a1 = x and ak = y.  Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.

Input: The first line contains integers n, m and w (1  ≤  n  ≤  1000, , 1 ≤ w ≤ 1000) — the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited.The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 1000) — the weights of the Hoses.The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106) — the beauties of the Hoses.The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct.

Output: Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.

Note: In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.

Sample Inputs:
3 1 5
3 2 5
2 4 2
1 2

4 2 11
2 4 6 6
6 4 2 1
1 2
2 3

Sample Outputs:
6

7

Solution (Python):
from sys import maxsize, stdout, stdin, stderr
mod = int(1000000000.0 + 7)
import sys

def I():
    return int(stdin.readline())

def lint():
    return [int(x) for x in stdin.readline().split()]

def S():
    return input().strip()

def grid(r, c):
    return [lint() for i in range(r)]
from collections import defaultdict, Counter
import math
import heapq
from heapq import heappop, heappush
import bisect
from itertools import groupby

def gcd(a, b):
    while b:
        a %= b
        tmp = a
        a = b
        b = tmp
    return a

def lcm(a, b):
    return a / gcd(a, b) * b

def check_prime(n):
    for i in range(2, int(n ** (1 / 2)) + 1):
        if not n % i:
            return False
    return True

def Bs(a, x):
    i = 0
    j = 0
    left = 0
    right = len(a)
    flag = False
    while left < right:
        mi = (left + right) // 2
        if a[mi] <= x:
            left = mi + 1
            i += 1
        else:
            right = mi
            j += 1
    if left > 0 and a[left - 1] == x:
        return (i - 1, j)
    else:
        return (-1, -1)

def nCr(n, r):
    return fact(n) // (fact(r) * fact(n - r))

def fact(n):
    res = 1
    for i in range(2, n + 1):
        res = res * i
    return res

def primefactors(n):
    num = 0
    while n % 2 == 0:
        num += 1
        n = n / 2
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        while n % i == 0:
            num += 1
            n = n // i
    if n > 2:
        num += 1
    return num
''

def ask(a):
    print('? {}'.format(a), flush=True)
    n = lint()
    return n

def dfs(i, p):
    (a, tmp) = (0, 0)
    for j in d[i]:
        if j != p:
            a += 1
            tmp += dfs(j, i)
    if a == 0:
        return 0
    return tmp / a + 1
(n, m, w) = lint()
we = lint()
b = lint()
ar = defaultdict(lambda : [])
vis = defaultdict(lambda : False)
d = defaultdict(lambda : [])
tow = defaultdict(lambda : 0)
tob = defaultdict(lambda : 0)
for i in range(m):
    (x, y) = lint()
    ar[x].append(y)
    ar[y].append(x)
cnt = 0
for i in range(1, n + 1):
    if not vis[i]:
        cnt += 1
        store = [i]
        while len(store):
            tmp = store.pop()
            if not vis[tmp]:
                d[cnt].append([we[tmp - 1], b[tmp - 1]])
                vis[tmp] = True
                for j in ar[tmp]:
                    store.append(j)
t = [[0] * (w + 1) for _ in range(cnt + 1)]
for i in range(1, cnt + 1):
    for j in range(1, w + 1):
        l = t[i - 1][j]
        (tow, tob) = (0, 0)
        for a in d[i]:
            if a[0] <= j:
                l = max(l, a[1] + t[i - 1][j - a[0]])
            tow += a[0]
            tob += a[1]
        if tow <= j:
            l = max(l, tob + t[i - 1][j - tow])
        t[i][j] = l
print(t[cnt][w])

Solution (Python):
import sys

class DSU:

    def __init__(self, weights):
        self.A = [[i, 0, w] for (i, w) in enumerate(weights)]
        self.size = len(self.A)

    def get(self, i):
        p = i
        while self.A[p][0] != p:
            p = self.A[p][0]
        j = self.A[i][0]
        while j != p:
            self.A[i][0] = p
            (i, j) = (j, self.A[j][0])
        return (p, self.A[p][2])

    def __getitem__(self, i):
        return self.get(i)[0]

    def union(self, i, j):
        (u, v) = (self[i], self[j])
        if u == v:
            return
        self.size -= 1
        if self.A[u][1] > self.A[v][1]:
            self.A[v][0] = u
            self.A[u][2] += self.A[v][2]
        else:
            self.A[u][0] = v
            self.A[v][2] += self.A[u][2]
            if self.A[u][1] == self.A[v][1]:
                self.A[v][1] += 1

    def __len__(self):
        return self.size

class pair(tuple):

    def __new__(self, T):
        return tuple.__new__(self, T)

    def __add__(self, f):
        return pair((self[0] + f[0], self[1] + f[1]))

    def __sub__(self, f):
        return pair((self[0] - f[0], self[1] - f[1]))

    def __neg__(self):
        return pair((-self[0], -self[1]))

def solve(n, m, w, fat, ass):
    D = DSU(map(pair, zip(fat, ass)))
    for line in sys.stdin:
        (u, v) = [int(x) - 1 for x in line.split()]
        D.union(u, v)
    A = list(range(n))
    A.sort(key=lambda x: D[x])
    din = [[0] * (w + 1)]
    num = {}
    for a in A:
        if D[a] not in num:
            num[D[a]] = len(num) + 1
            din.append([0] * (w + 1))
            (x, y) = D.get(a)[1]
            for j in range(min(x, w + 1)):
                din[-1][j] = din[-2][j]
            for j in range(x, w + 1):
                din[-1][j] = max(din[-2][j], din[-2][j - x] + y)
        i = num[D[a]]
        for j in range(fat[a], w + 1):
            din[i][j] = max(din[i][j], din[i - 1][j], din[i - 1][j - fat[a]] + ass[a])
    return din[-1][-1]
(n, m, w) = map(int, input().split())
fat = [int(x) for x in input().split()]
ass = [int(x) for x in input().split()]
print(solve(n, m, w, fat, ass))

Solution (Python):
(n, m, W) = map(int, input().split())
w = [0] + list(map(int, input().split()))
b = [0] + list(map(int, input().split()))
g = [[] for _ in range(n + 1)]
for _ in range(m):
    (v1, v2) = map(int, input().split())
    g[v1].append(v2)
    g[v2].append(v1)
dp = [0] * (W + 1)

def dfs(v):
    all = []
    all.append((w[v], b[v]))
    used[v] = False
    for i in range(len(g[v])):
        next = g[v][i]
        if used[next] == False:
            continue
        all.extend(dfs(next))
    return all
used = [True] * (n + 1)
for i in range(1, n + 1):
    if not used[i]:
        continue
    all = dfs(i)
    sumAll = sum((val[1] for val in all))
    weightAll = sum((val[0] for val in all))
    for _W in range(W - 1, -1, -1):
        if _W + weightAll <= W:
            dp[_W + weightAll] = max(dp[_W + weightAll], dp[_W] + sumAll)
        for elem in range(len(all)):
            if _W + all[elem][0] <= W:
                dp[_W + all[elem][0]] = max(dp[_W + all[elem][0]], dp[_W] + all[elem][1])
answer = max(dp)
print(answer)