参考资料:http://www.hawstein.com/posts/dp-novice-to-advanced.html
硬币问题:
int main(){
int num[3]={1,3,5};
int now=0;
int d[15];
for(int i=0;i<=11;i++)
d[i]=i;
for(int i=0;i<=11;i++){
for(int j=0;j<3;j++){
if(num[j]<=i&&d[i-num[j]]+1<d[i])
d[i]=d[i-num[j]]+1;
}
}
for(int i=0;i<12;i++)
printf("%d ",d[i]);
printf("\n");
return 0;
}
最长非降子序列:
int main(){
int num[6] = {5,3,4,8,6,7};
int d[6];
for(int i=0;i<6;i++) d[i]=1;
for(int i=1;i<6;i++){
if(num[i-1]<num[i])
d[i]=d[i-1]+1;
else
d[i]=d[i-1];
}
for(int i=0;i<6;i++)
printf("%d ",d[i]);
printf("\n");
return 0;
}
TopCoder: Zigzag
#include <cstdio>
#include <iostream>
using namespace std;
int main(){
int n,num[105],d[105];
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&num[i]);
for(int i=0;i<n;i++) d[i]=1;
int m = num[0];
int count=1;
for(int i=1;i<n;i++){
if(count){
if(m<num[i]) {d[i]=d[i-1]+1;m=num[i];count=0;}
else d[i]=d[i-1];
}else{
if(m>num[i]) {d[i]=d[i-1]+1;m=num[i];count=1;}
else d[i]=d[i-1];
}
}
int maxN = 0;
for(int i=0;i<n;i++)
maxN = max(maxN,d[i]);
cout<<"Result "<<maxN<<endl;
return 0;
}
TopCoder BadNeighbors:
#include<cstdio>
#include<iostream>
using namespace std;
int n,num[500],sum[500];
int getAnswer(int i1,int i2){
if(i1>i2) return 0;
sum[i2] = max(getAnswer(i1+1,i2),getAnswer(i1+2,i2)+num[i1]);
return sum[i2];
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++) {scanf("%d",&num[i]);sum[i]=num[i];}
int answer = max(getAnswer(0,n-2),getAnswer(1,n-1));
printf("Answer: %d\n",answer);
return 0;
}
从这里开始就是使用了递归的动态规划