【uva 11054】Wine trading in Gergovia(算法效率--等价转换)

题意:N个等距村庄,买(>0)卖(<0)酒,供需平衡,运K则需K劳动力。问所需的最小劳动力。

解法:由于运出或运入1的都需经过2,所以无论如何,都可以等价于从2本身运入或运出。因此可以将1和2合并,2一定要运a1(小心:确保 i 的劳动力消耗量是由 i 之前,即 i-1 得到的),记a1+a2为现在自己的所需量。其他同理。

注意——理清关系,算劳动力时要用绝对值。

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<cstring>
 4 #include<iostream>
 5 using namespace std;
 6 typedef long long LL;
 7 
 8 LL mabs(LL x) {return x>0?x:-x;}
 9 int main()
10 {
11     int n;
12     while (1)
13     {
14       scanf("%d",&n);
15       if (!n) break;
16       LL x,last=0,ans=0;
17       for (int i=1;i<=n;i++)
18       {
19         scanf("%lld",&x);
20         ans+=mabs(last);
21                 last+=x;
22       }
23       printf("%lld
",ans);
24     }
25     return 0;
26 }
原文地址:https://www.cnblogs.com/konjak/p/5975951.html