我爲一個問題寫了一個遞歸DP解決方案。這個解決方案對於一些測試案例來說是失敗的(它只是一次過度計數或者計數不足)。我如何才能引用或打印那些導致我最終答案的國家?簡單的方法來跟蹤遞歸調用?
的遞歸函數是這樣的。它需要4個輸入。如果以前評估過某個特定狀態,則返回std::map
的解決方案,否則將對其進行評估。該解決方案遞歸地返回每個狀態的min
值。
這是解決Play the DragonGoogle CodeJam 2017 1A的
int hd,ad,hk,ak,b,d;
int inf=1e9+1;
map< tuple<int,int,int,int>, int > dp;
int count(int hld, int hlk, int atd, int atk){
if(dp[make_tuple(hld,hlk,atd,atk)]){
return dp[make_tuple(hld,hlk,atd,atk)];
}
else{
if(hlk<=0){
return 0;
}
if(hld<=0){
return inf;
}
if(hlk-atd<=0){
return 1;
}
if(hld==hd-atk){
if(b==0||d==0){
if(b==0&&d!=0){
return dp[make_tuple(hld,hlk,atd,atk)] = 1 + min(
count(hld-atk,hlk-atd,atd,atk),
count(hld-atk+d,hlk,atd,(atk-d)<0?0:(atk-d))
);
}
if(b!=0&&d==0){
return dp[make_tuple(hld,hlk,atd,atk)] = 1 + min(
count(hld-atk,hlk-atd,atd,atk),
count(hld-atk,hlk,atd+b,atk)
);
}
return dp[make_tuple(hld,hlk,atd,atk)] = 1 + count(hld-atk,hlk-atd,atd,atk);
}
return dp[make_tuple(hld,hlk,atd,atk)] = 1 + min(
count(hld-atk,hlk-atd,atd,atk),
min(
count(hld-atk,hlk,atd+b,atk),
count(hld-atk+d,hlk,atd,(atk-d)<0?0:(atk-d))
)
);
}
if(b==0||d==0){
if(b==0&&d!=0){
if(atk<=0){
return dp[make_tuple(hld,hlk,atd,atk)] = 1 + count(hld-atk,hlk-atd,atd,atk);
}
return dp[make_tuple(hld,hlk,atd,atk)] = 1 + min(
count(hld-atk,hlk-atd,atd,atk),
min(
count(hd-atk,hlk,atd,atk),
count(hld-atk+d,hlk,atd,(atk-d)<0?0:(atk-d))
)
);
}
if(b!=0&&d==0){
return dp[make_tuple(hld,hlk,atd,atk)] = 1 + min(
count(hld-atk,hlk-atd,atd,atk),
min(
count(hld-atk,hlk,atd+b,atk),
count(hd-atk,hlk,atd,atk)
)
);
}
if(atk<=0){
return dp[make_tuple(hld,hlk,atd,atk)] = 1 + count(hld-atk,hlk-atd,atd,atk);
}
return dp[make_tuple(hld,hlk,atd,atk)] = 1 + min(
count(hld-atk,hlk-atd,atd,atk),
count(hd-atk,hlk,atd,atk)
);
}
if(atk<=0){
return dp[make_tuple(hld,hlk,atd,atk)] = 1 + min(
count(hld-atk,hlk-atd,atd,atk),
count(hld-atk,hlk,atd+b,atk)
);
}
return dp[make_tuple(hld,hlk,atd,atk)] = 1 + min(
count(hld-atk,hlk-atd,atd,atk),
min(
count(hld-atk,hlk,atd+b,atk),
min(
count(hd-atk,hlk,atd,atk),
count(hld-(atk-d)<0?0:(atk-d),hlk,atd,(atk-d)<0?0:(atk-d))
)
)
);
}
}