zoukankan      html  css  js  c++  java
  • 1489 ACM 贪心

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=1489

    题意:为负数表示买酒,正数表示买酒,每两家人之间为one unit of work.问最小的work

    思路:从左向右依次把久给离自己最近的买卖家就好。

    代码算法原理如下:

    以题目举的例子为例:

    5

    5  -4  1  -3  1

    5    -5+1   -1+2    -2-1   1+0

    {(5 -5)+(1  -1)+(2  -2)-(1  1)+0}

    每个数都可以拆分成如上两个数,相邻的两个数 互相供应。(之所以可以这样拆,是因为题目的要求:one unit of work.)

    从左到右,计算的过程为:5+|1|+|2|+|-1|+|0|=9,实际就是5 .-5,1.-1,这样成对的数,依次加一个就好。

    扩展:

    绝对值:

    #include 

    int abs(int i);                      // 处理int类型的取绝对值

    double fabs(double i);  //处理double类型的取绝对值

    float fabsf(float i);              /处理float类型的取绝对值

    code:

    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>
     
    using namespace std;
     
    int main()
    {
        int n, a;
        while(cin>>n && n) {
            long long sum = 0, ans = 0;
     
            for(int i=1; i<=n; i++) {
                scanf("%d", &a);
     
                sum += a;
                ans += abs(sum);
            }
     
            cout<<ans<<endl;
        }
     
        return 0;
    }
  • 相关阅读:
    os.remove some jpgs
    shutil.rmtree, os.path, delete sub-folders, format
    How to create folder
    valgrind
    gstream
    TP TN FP FN
    tensor flow
    接口中静态方法和默认方法
    JAVA基础09
    JAVA基础08
  • 原文地址:https://www.cnblogs.com/CheeseIce/p/9688424.html
Copyright © 2011-2022 走看看