题目链接:点击查看
题目大意:给出一个范围 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;
}