1、如题,HDU ACM-1003最大数问题。链接地址:http://acm.hdu.edu.cn/showproblem.php?pid=1003
该题考察的是经典算法分治法,利用分治法求最大子段和。如下图:
AC代码如下:
#include <stdio.h>
int getMaxNum(int *pArray, int nStart, int nEnd, int *pStart, int *pEnd)
{
if (nEnd - nStart == 0)
{
*pStart = nEnd;
*pEnd = nEnd;
return pArray[nStart];
}
int nPreStart;
int nPreEnd;
int nPreMid = (nStart + nEnd) / 2;
int PreMax = getMaxNum(pArray, nStart, nPreMid, &nPreStart, &nPreEnd);
int nAfterStart;
int nAfterEnd;
int nAfterMid = (nStart + nEnd) / 2 + 1;
int AfterMax = getMaxNum(pArray, nPreMid + 1, nEnd,&nAfterStart, &nAfterEnd);
int nSumA = 0;
int nSum = pArray[nPreMid];
int nStartA = nPreMid;
{
nSum = pArray[nPreMid];
for (int i = nPreMid; i >= nStart; i--)
{
nSumA += pArray[i];
if (nSumA >= nSum)
{
nSum = nSumA;
nStartA = i;
}
}
nSumA = nSum;
}
int nSumB = 0;
int nEndB = nPreMid + 1;
{
nSum = pArray[nPreMid + 1];
for (int i = nPreMid + 1; i <= nEnd; i++)
{
nSumB += pArray[i];
if (nSumB >= nSum)
{
nSum = nSumB;
nEndB = i;
}
}
nSumB = nSum;
}
int nSumMax = nSumA + nSumB;
if (PreMax > nSumMax)
{
nSumMax = PreMax;
nStartA = nPreStart;
nEndB = nPreEnd;
}
if (AfterMax > nSumMax)
{
nSumMax = AfterMax;
nStartA = nAfterStart;
nEndB = nAfterEnd;
}
*pStart = nStartA;
*pEnd = nEndB;
return nSumMax;
}
int main()
{
int T;
scanf("%d", &T);
int *arr[20] = {0};
int nNum[20] = {0};
for (int n = 0; n < T; n++)
{
scanf("%d", &nNum[n]);
arr[n] = new int[nNum[n]];
for (int i = 0; i < nNum[n]; i++)
{
scanf("%d", &arr[n][i]);
}
}
for (int n = 0; n < T; n++)
{
int nStart = 0;
int nEnd = 0;
int nMax = getMaxNum(arr[n], 0, nNum[n]-1, &nStart, &nEnd);
printf("Case %d:\n", n + 1);
if (n == T - 1)
{
printf("%d %d %d\n", nMax, nStart + 1, nEnd + 1);
}
else
{
printf("%d %d %d\n\n", nMax, nStart + 1, nEnd + 1);
}
}
return 0;
}