B
模拟
#include<bits/stdc++.h> #define inf 0x3f3f3f3f #define MAX 1000001 #define inf 0x3f3f3f3f #define ll long long #define MAX 1000001 const ll N = 1e5+7; const ll mod = 1e9+7; using namespace std; ll w[N],b[N],ans=0,vis[N],n,m; int main(){ scanf("%lld%lld",&n,&m); for(int i=1;i<=n;++i) scanf("%lld",&w[i]); for(int i=1;i<=m;++i){ scanf("%lld",&b[i]); for(int j=1;j<=n;++j) vis[j]=0; for(int j=i-1;j;--j){ if(b[j]==b[i]) break; if(vis[b[j]]==0){ vis[b[j]]=1; ans+=w[b[j]]; } } } printf("%lld ",ans); return 0; }
C
树形dp
#include<bits/stdc++.h> #define inf 1e18 #define ll long long #define MAX 1000001 const ll N = 2e5+7; const ll mod = 1e9+7; using namespace std; ll n,a[N],s[N],mx[N],ans=-inf; vector<ll>G[N]; void dfs(int u,int fa){ ll mx2=-inf; s[u]=a[u];mx[u]=-inf; for(int i=0;i<G[u].size();++i){ int v=G[u][i]; if(v==fa) continue; dfs(v,u); s[u]+=s[v]; if(mx[v]>mx[u]){ mx2=mx[u],mx[u]=mx[v]; } else if(mx[v]>mx2){ mx2=mx[v]; } } ans=max(ans,mx[u]+mx2); mx[u]=max(mx[u],s[u]); } int main(){ scanf("%lld",&n); for(int i=1;i<=n;++i) scanf("%lld",&a[i]); for(int i=1;i<n;++i){ ll u,v;scanf("%lld %lld",&u,&v); G[u].push_back(v); G[v].push_back(u); } dfs(1,0); if(ans==-inf) printf("Error "); else printf("%lld ",ans); return 0; }