您的位置:首页 > 其它

【Coding】 动规, 这个, 逻辑不严谨呀同学, 多多练习。

2014-05-06 22:44 363 查看
今天继续练习DP初级版。

依旧照葫芦画瓢的写DP。刚刚分析的时候,发现不很难,毕竟初级的问题,写过一个之后,相类似的很容易模仿。

思想的原理确实更加深刻了。但是运用到不同的题目上,又各自有各自的特点。

不同的题目就是细节上,判定的条件上不同了。 以后争取掌握更快的调试方法,迅速找到程序中漏掉的细节,加以补救。

补充逻辑中欠缺,有的时候会觉得是东补西贴呢。

c语言的版本,所以比较长,不过是用一维数组解决的,另外的一种思想勒。

// the key problem is to judge the front stratege has number 1's donation decication
/*
the test data:
6
10 3 2 5 7 8
10
1 2 3 4 5 1 2 3 4 5
7
7 7 7 7 7 7 7
2
11 15

*/

#include <stdio.h>
#define M 43
int f[M];

//to get the max value, then return if it has the number 1 to dedicate
//into the resolve
int max(int x,int y,int flag,int current)
{
if( x > y)
{
return x;
}
else
{
f[current] = flag;
return y;
}
}

int maxthree(int x,int y,int z)
{
if(x>y && x>z)
{
return x;
}
else if( y>z)
{
return y;
}
else
return z;
}

int main()
{
int input[M];
int d[M];

int i;
int n;
scanf("%d",&n);
for(i=0 ;i< n; i++)
{
scanf("%d",&input[i]);
d[i] = input[i];
f[i]=0;
}
int j;
f[0] = 1;
for( i=1 ; i<n-1 ;i++)
{
for( j=0 ; j<i;  j++)
{
//if it can be combined with forward, then compares with the Added result
if( i-j > 1)
{
d[i] = max(d[i], d[j] + input[i],f[j],i);
}

// else it just compares with the forward, but not added
else
{
d[i] = max(d[i], d[j],f[j],i);
}
}
/*
if( isadd == 0)
{
for(j=0 ; j< i ; j++)
{
d[i]  = max(d[i], d[j] , f[j], i);
}

}*/
}
for(i=0 ; i < n-1 ; i++)
{
if( f[i] == 0)
{
d[n-1] = max( d[n-1], d[i]+input[n-1], f[i], n-1);
}
else if(i != n-2)
{
//前面的方案,本身的值,前面的方案去掉开始的值+本身
d[n-1] = maxthree( d[n-1], d[i], d[i]-d[0]+input[n-1]);
}
else
{
d[n-1] = max( d[n-1], d[i], f[i], n-1);
}
}
/*
for(i=0 ; i < n; i++)
{
printf("[%d]%d,",i,d[i]);
}
printf("\n");
for(i=0 ; i < n; i++)
{
printf("[%d]%d,",i,f[i]);
}*/
printf("%d",d[n-1]);
getchar();
getchar();
getchar();
return 0;
}
网上搜到的另外一种算法,二维数组实现,把首位两个不能共存的元素分开了。

public class BadNeighbors {
public int maxDonations(int[] donations) {
int len = donations.length;
if (len == 0) return 0;
if (len == 1) return donations[0];
if (len == 2) return Math.max(donations[0], donations[1]);

int[][] matrix = new int[len][2];
// len >= 3
// [i][0] means max from 0..i-1
// [i][1] means max from 1..i
matrix[1][0] = donations[0];
matrix[1][1] = donations[1];
matrix[2][0] = Math.max(donations[0], donations[1]);
matrix[2][1] = Math.max(donations[1], donations[2]);

for (int i = 3; i < donations.length; i++) {
matrix[i][0] = Math.max(matrix[i-1][0], matrix[i-2][0] + donations[i-1]);
matrix[i][1] = Math.max(matrix[i-1][1], matrix[i-2][1] + donations[i]);
}

return Math.max(matrix[len-1][0], matrix[len-1][1]);
}
}


发现我的编码习惯就是工程编码的习惯,括号拉的长长的,结构拉的比较长而松散。嘿嘿,不过在工程中看着还挺舒服的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐