zoukankan      html  css  js  c++  java
  • 光庭杯第九题

    求子数组绝对值的和的最小值

    动归

    #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;
    }

  • 相关阅读:
    c# 图像转化成灰度图
    文件操作 流
    GBK UTF8 GB2312 流
    助力奥巴马,拯救大气层
    ASP.NET 缓存技术
    GridView 和 ViewState 来实现条件查寻
    把日期按指定格式输出
    创业灵感淘宝网
    文件_上传_下载
    java23种设计模式与追MM
  • 原文地址:https://www.cnblogs.com/hxsyl/p/2450590.html
Copyright © 2011-2022 走看看