求子数组绝对值的和的最小值
动归
#include<stdio.h>
#include<stdlib.h>
#define N 1001
unsigned long int a[N], f[N];
unsigned long int n;
unsigned long int Abs(unsigned long int x)
{
return x>0?x:-x;
}
unsigned long int dp()
{ /*
if (|f(x)+a(x+1)|<|a(x+1)|)
f(x+1) = f(x)+a(x+1)
else f(x+1) = a(x+1)
最后求出min(|f(0)|........|f(j)|)*/
unsigned long int i;
unsigned long int min;
f[0]=a[0];
for(i=0;i<n;i++)
{
if(Abs(a[i+1]+f[i]) < Abs(a[i+1])) f[i+1] = a[i+1]+f[i];
else f[i+1] = a[i+1];
}
min = Abs(f[0]);
for(i=1;i<n;i++)
if(min>Abs(f[i]))
min = Abs(f[i]);
return min;
}
int main()
{
unsigned long int i,j,T;
unsigned long int m=1;
scanf("%ld",&T);
while(T--)
{
scanf("%ld",&n);
for(i=0;i<n;i++)
{
scanf("%ld",&a[i]);
if(i>0)
f[i] = f[i-1]+a[i];
else f[0] = a[0];
}
printf("Case %ld: %ld\n",m,dp());
m++;
}
system("pause");
return 0;
}
超时代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define N 1001
int leastsubsequencesum(int a[],int n)
{
int i,j,k;int sum,min=10001;
for(i=0;i<n;i++)
for(j=i;j<n;j++)
{
sum=0;
for(k=i;k<=j;k++)
sum+=a[k];
sum=abs(sum);
if(sum<min)
min=sum;
}
return min;
}
int main()
{
int i,j,T,n;int a[N];int s,k;int m=1;
memset(a,0,sizeof(a));
scanf("%d",&T);
k=T;
while(T--)
{
if(m<=k)
{
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
s=leastsubsequencesum(a,n);
printf("Case %d: %d\n",m,s);
m++;
}
//T--;
}
return 0;
}