D. Arpa's weak amphitheater and Mehrdad's valuable Hoses
time limit per test
memory limit per test
input
output
Just to remind, girls in Arpa's land are really nice.
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.
w
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
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.
n integers w1, w2, ..., wn (1 ≤ wi) — the weights of the Hoses.
n integers b1, b2, ..., bn (1 ≤ bi ≤ 106) — the beauties of the Hoses.
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 xiand yi are friends. Note that friendship is bidirectional. All pairs (xi, yi)
Output
w.
Examples
input
3 1 53 2 5 2 4 2 1 2
output
6
input
4 2 112 4 6 6 6 4 2 1 1 2 2 3
output
7
用深搜求出n组朋友,对于一组朋友来说,可以选择其中的一个朋友,或者整组。再把每一组当作物品,进行求解
背包问题
#include <bits/stdc++.h>
#define MOD 1000000007
#define maxn 100005
using namespace std;
typedef long long ll;
int dp[2][1005], vis[1005];
int w[1005], b[1005], h, sum1, sum2;
vector<int> v[1005];
int n, m, ww, a, bb;
void dfs(int j){
for(int i = ww; i >= w[j]; i--){
dp[h][i] = max(dp[h^1][i-w[j]] + b[j], dp[h][i]);
}
vis[j] = 1;
sum1 += w[j];
sum2 += b[j];
for(int i = 0; i < v[j].size(); i++){
if(vis[v[j][i]] == 0){
dfs(v[j][i]);
}
}
}
int main(){
// freopen("in.txt", "r", stdin);
scanf("%d%d%d", &n, &m, &ww);
for(int i = 1; i <= n; i++)
scanf("%d", w+i);
for(int j = 1; j <= n; j++)
scanf("%d", b+j);
for(int i = 1; i <= m; i++){
scanf("%d%d", &a, &bb);
v[a].push_back(bb);
v[bb].push_back(a);
}
for(int i = 1; i <= n; i++){
if(vis[i] == 0){
dfs(i);
for(int j = ww; j >= sum1; j--){
dp[h][j] = max(dp[h^1][j-sum1] + sum2, dp[h][j]);
}
for(int j = ww; j >= 0; j--)
dp[h^1][j] = dp[h][j];
sum1 = sum2 = 0;
}
}
printf("%d\n", dp[h][ww]);
return 0;
}