经过我的不懈努力,放弃了上边用二维数组实现的想法,终于用一维数组搞定实现了。
下边是源代码,实验过好几遍了,结果都没错。
#include
#include
struct triangle
{
int element;
int sum;
}*array;
int Count( struct triangle *arr, int m, int s )
{
int i, j, temp;
int result = 0;
int n = 0;
for( i = 0; i <= (m - 1) * (m - 2) / 2; i = i + n )
{
for( j = 0; j <= n; j ++ )
{
temp = arr[i + j].sum + arr[i + j + n + 1].element;
if( temp > arr[i + j + n + 1].sum )
arr[i + j + n + 1].sum = temp;
temp = arr[i + j].sum + arr[i + j + n + 1 + 1].element;
if( temp > arr[i + j + n + 1 + 1].sum )
arr[i + j + n + 1 + 1].sum = temp;
}
n++;
}
for( i = m * (m - 1) / 2; i < s; i ++ )
{
if( arr[i].sum > result )
result = arr[i].sum;
}
return result;
}
void main()
{
int i;
int degree, size;
int result;
printf( "Please input the degree of triangle:" );
while(1)
{
scanf( "%d", °ree );
if( degree > 1 && degree <= 100 )
break;
printf( "Error input!Please try again.\n" );
printf( "Please input the degree of triangle:" );
}
size = degree * (1 + degree ) / 2;
array = (struct triangle *)malloc( size * sizeof(struct triangle) );
printf( "Please input the elements of triangle:\n" );
for( i = 0; i < size; i ++ )
{
scanf( "%d", &array[i].element );
array[i].sum = array[i].element;
}
result = Count( array , degree , size );
free(array);
printf( "The maximum is %d\n", result );
}
[此贴子已经被作者于2007-6-14 20:03:03编辑过]