CodeForces - 1485E Move and Swap(树形dp)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1485E Move and Swap(树形dp)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一棵有根樹,每個節(jié)點都有權值,滿足所有葉子結點到根節(jié)點的距離相同,初始時在根節(jié)點有兩個硬幣,分別是紅色和藍色,每次可以執(zhí)行如下操作:
問如何移動可以使得貢獻之和最大
題目分析:不算難的一道樹形 dpdpdp,因為藍色硬幣可以是下一層的任意節(jié)點,所以只需要關注紅色硬幣移動的路線就可以了,不妨設 dpidp_idpi? 為紅色硬幣在點 iii 時移動到葉子結點的最大貢獻和,選擇自底向上轉移,這樣就將原樹中的節(jié)點劃分成不同層次之間的轉移了。
分成兩種情況討論:
乍一看轉移的復雜度不是很可觀,但是這些東西是可以預處理的,第一種情況我們只需要維護一下 ama_mam? 的最小值和最大值輔助轉移即可,第二種情況需要預處理一下 dpm?amdp_m-a_mdpm??am? 和 dpm+amdp_m+a_mdpm?+am? 的最大值輔助轉移就好啦
代碼:
// Problem: E. Move and Swap // Contest: Codeforces - Codeforces Round #701 (Div. 2) // URL: https://codeforces.com/contest/1485/problem/E // Memory Limit: 256 MB // Time Limit: 2000 ms // // Powered by CP Editor (https://cpeditor.org)// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<list> #include<unordered_map> #define lowbit(x) x&-x using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const LL inf=0x3f3f3f3f3f3f3f3f; const int N=1e6+100; int fa[N],max_deep; LL dp[N],a[N]; vector<int>node[N],d[N]; void dfs(int u,int f,int dep) {max_deep=max(max_deep,dep);fa[u]=f;d[dep].push_back(u);for(auto v:node[u]) {dfs(v,u,dep+1);} } void init(int n) {for(int i=1;i<=n;i++) {node[i].clear();d[i].clear();}memset(dp,0,sizeof(LL)*(n+5));max_deep=0; } int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);int w;cin>>w;while(w--) {int n;read(n);init(n);for(int i=2;i<=n;i++) {int fa;read(fa);node[fa].push_back(i);}for(int i=2;i<=n;i++) {read(a[i]);}dfs(1,-1,1);for(int i=max_deep;i>1;i--) {//不交換LL mmax=-inf,mmin=inf;for(auto u:d[i]) {mmax=max(mmax,a[u]);mmin=min(mmin,a[u]);}for(auto u:d[i]) {dp[fa[u]]=max(dp[fa[u]],dp[u]+max(llabs(a[u]-mmax),llabs(a[u]-mmin)));}//交換LL mmax1=-inf,mmax2=-inf;for(auto u:d[i]) {mmax1=max(mmax1,dp[u]+a[u]);mmax2=max(mmax2,dp[u]-a[u]);}for(auto u:d[i]) {dp[fa[u]]=max(dp[fa[u]],mmax1-a[u]);dp[fa[u]]=max(dp[fa[u]],mmax2+a[u]);}}cout<<dp[1]<<endl;}return 0; } 超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的CodeForces - 1485E Move and Swap(树形dp)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1486F P
- 下一篇: CodeForces - 1485F C