#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define vi vector<int>
#define pb push_back
#define all(a) a.begin(),a.end()
const int mxn = 1001;
const ll inf = 1e18;
vector<int> g[mxn];
int val[mxn], sub[mxn];
ll dp[mxn][mxn];
ll dp2[mxn][mxn];
bool vis[mxn];
void dfs(int u){
vis[u] = 1;
sub[u] = 1;
fill(dp[u],dp[u]+mxn,inf);
fill(dp2[u],dp2[u]+mxn,inf);
dp2[u][0] = 0;
dp[u][1] = val[u];
for(auto v : g[u]) if(!vis[v]){
dfs(v);
for(int i = sub[u]+sub[v]; i; i--)
for(int j = max(0,i-sub[v]); j <= min(i,sub[u]); j++){
if(j){
dp[u][i] = min(dp[u][i],dp[u][j] + dp[v][i-j]);
if(j>1) dp[u][i] = min(dp[u][i],dp[u][j] + dp2[v][i-j]);
if(i-j>0) dp[u][i] = min(dp[u][i],dp[u][j] + dp2[v][i-j-1] + val[v]);
if(i-j>0 && j>0) dp[u][i] = min(dp[u][i],dp2[u][j-1] + dp[v][i-j] + val[u]);
}
dp2[u][i] = min(dp2[u][i],dp2[u][j] + dp2[v][i-j]);
if(i-j > 1) dp2[u][i] = min(dp2[u][i],dp2[u][j] + dp[v][i-j]);
}
sub[u] += sub[v];
}
}
void solve(){
int n,m,q; cin >> n >> m;
for(int i = 1; i <= n; i++)
cin >> val[i];
for(int i = 0; i < m; i++){
int u,v; cin >> u >> v;
g[u].pb(v); g[v].pb(u);
}
vector<ll> res(n+1,inf);
res[0] = 0;
int sz = 0;
for(int i = 1; i <= n; i++) if(!vis[i]){
dfs(i);
for(int j = sz+sub[i]; j >= 0; j--)
for(int k = max(0,j-sub[i]); k <= min(j,sz); k++){
if(j-k>1) res[j] = min(res[j],res[k] + dp[i][j-k]);
res[j] = min(res[j],res[k] + dp2[i][j-k]);
}
sz += sub[i];
}
for(int i = n; i; i--)
res[i-1] = min(res[i-1],res[i]);
cin >> q;
for(int i = 0; i < q; i++){
ll x; cin >> x;
cout << upper_bound(all(res),x) - res.begin() - 1 << '\n';
}
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
int t = 1;
// cin >> t;
while(t--){solve();}
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |