The condition of choosing a subset of neighbors to pass down the piece is highly similar to a backpack problem, where each neighbor has a value contribution and a backpack weight.
Let us denote f [ i ] f[i] f[i] as the maximum number of operations possible when one piece is put on node i i i. Then, f [ i ] f[i] f[i] can be acquired by performing a 01 backpack process with its neighbors, with their w w w value as weight and f f f value as value.
This calculation can be completed in O ( W m a x ⋅ m ) \mathcal O(W_{max} \cdot m) O(Wmax⋅m) time if we start from the nodes with smallest w w w values. The final answer would be ∑ f [ i ] ⋅ a [ i ] \sum f[i]\cdot a[i] ∑f[i]⋅a[i]
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<map>
using namespace std;
const long long Maxn=5e3+10;
struct node{
long long pos,val;
bool operator <(const node &x)const
{
return x.val>val;
}
}s[Maxn];
vector <long long> e[Maxn];
long long a[Maxn],w[Maxn];
long long f[Maxn],g[Maxn];
long long n,m,ans;
inline long long read()
{
long long s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
return s*w;
}
int main()
{
// freopen("in.txt","r",stdin);
n=read(),m=read();
while(m--)
{
long long x=read(),y=read();
e[x].push_back(y);
e[y].push_back(x);
}
for(long long i=1;i<=n;++i)
{
w[i]=read();
s[i]=node{i,w[i]};
}
for(long long i=1;i<=n;++i)
a[i]=read();
sort(s+1,s+1+n);
for(long long k=1;k<=n;++k)
{
long long x=s[k].pos;
memset(g,0,sizeof(g));
for(long long i=0;i<e[x].size();++i)
{
long long y=e[x][i];
if(w[y]>=w[x])continue;
for(long long j=w[x];j>=w[y];--j)
g[j]=max(g[j],g[j-w[y]]+f[y]);
}
for(long long i=1;i<w[x];++i)
f[x]=max(f[x],g[i]);
++f[x];
ans+=f[x]*a[x];
}
// for(long long i=1;i<=n;++i)
// printf("%d ",f[i]);
// putchar('\n');
printf("%lld\n",ans);
return 0;
}