題目鏈接:點擊查看
題目大意:給出一個範圍 n ,在其中有一個數字 x ∈ [ 1 , n ] ,你需要猜這個數字,如果猜錯了,代價就是猜的這個數字的權值,並會得知是猜大了還是猜小了,問猜到任意一個數字最大的代價之和最小是多少
題目分析:一開始以爲是二分,結果一直WA,後來zx學長用區間dp秒了之和,才意識到這原來是個dp題。。
dp[ l ][ r ] 代表在區間 [ l , r ] 內猜數字的答案,那麼最終答案顯然就是 dp[ 1 ][ n ] 了,因爲如果區間長度爲 1 的話,猜一次肯定能猜中,所以初始化 dp[ i ][ i ] = 0 ,對於 dp[ l ][ r ] ,初始化爲 min( dp[ l + 1 ][ r ] + l , dp[ l ][ r - 1 ] + r ) ,意義就是選擇猜 l 這個數,得知剩下的數要比 l 大,或者是猜 r 這個數,得知剩下的數要比 r 小
轉移的話就是枚舉中間點 k ,意思就是猜數字 k 爲多少,然後擇優轉移就好了
代碼:
#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>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const LL inf=0x3f3f3f3f;
const int N=110;
int dp[N][N];
int main()
{
#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);
int n;
scanf("%d",&n);
for(int len=2;len<=n;len++)
for(int l=1;l+len-1<=n;l++)
{
int r=l+len-1;
dp[l][r]=min(dp[l+1][r]+l,dp[l][r-1]+r);
for(int k=l+1;k<r;k++)
{
dp[l][r]=min(dp[l][r],max(dp[l][k-1],dp[k+1][r])+k);
}
}
printf("%d\n",dp[1][n]);
return 0;
}