hdu 1087 簡單dp,hdu1087dp
思路和2391一樣的。。
<span style="font-size:24px;">#include<stdio.h>#include<string.h>#include<iostream>#include<algorithm>using namespace std;const int inf=(0x7f7f7f7f);int main(){ int a; int s[10005]; int w[10005]; while(scanf("%d",&a)&&a) { for(int i=1;i<=a;i++) scanf("%d",&s[i]); memset(w,0,sizeof(w)); for(int i=0;i<=a-1;i++) for(int j=i+1;j<=a;j++) { if(s[i]<s[j]) { if(w[j]<s[j]+w[i]) w[j]=s[j]+w[i]; } } int ans=-22; for(int i=0;i<=a;i++) if(w[i]>ans) ans=w[i]; printf("%d\n",ans); } return 0;}</span>
hdu 1087 想知道這個為何錯
你的演算法是貪心,是錯的
要DP
比方說這個case
5 1 9 6 7 8
正確答案是22 序列是 1 6 7 8
但是你的程式會輸出21,序列是6 7 8
正確做法
#include<stdio.h>
int main()
{
long n,i,a[1005],j;
__int64 s[1005],m;
while(scanf("%ld",&n),n)
{
for(i=0;i<n;i++)
scanf("%ld",&a[i]);
for(i=0;i<n;i++) //這是從i開始計算向後的上升的序列的
{
s[i]=a[i];
for(j=i-1;j>=0;j--)
{
if(a[j]<a[i] && s[j] + a[i] > s[i])
s[i] = s[j] + a[i];
}
}
m=s[0];
for(i=0;i<n;i++) //求出序列和中最大的。
if(m<s[i]) m=s[i];
printf("%I64d\n",m);
}
}
大牛們幫我看看杭電acm1087這道題,這是一道DP,開始想先暴力試試,但為啥WA?其實逾時我都可以想通,
Sample Input
11 1 11 2 3 4 5 6 7 8 9 10
0
Sample Output
55