Gergovia的酒交易B805(移動紙牌)

來源:互聯網
上載者:User

標籤:title   範圍   namespace   整數   bre   ring   mat   等於   ble   

 

試題描述

 直線上有 n 個等距的村莊,每個村莊要麼買酒,要麼賣酒。設第 i 個村莊對酒的需求為 ai (-1000<=ai<=1000),其中ai>0表示買酒,ai<0表示賣酒。所有村莊供需平衡,即所有 ai 之和等於0。把 k 個單位的酒從一個村莊運到相鄰村莊需要 k 個單位的勞動力。計算最少需要多少勞動力可以滿足所有村莊的需求。輸出保證在 64 位元帶正負號的整數的範圍內。

輸入
若干組資料,每組資料為兩行。
對於每組資料,第一行有一個整數N,表示有N個酒窖,第二行有N個整數,從a1,a2一直到an。
輸入的最後以0結尾。
輸出
每組資料一行,每行一個整數,表示總費用。
輸入樣本
10
3 -1 -2 9 -4 -1 -7 9 -7 1
5
1000 -1000 1000 0 -1000
0
輸出樣本
33
3000
其他說明
資料範圍:2 <= n <= 100 000
 

大概的思路:從最左邊的往右推。因為線性村莊中最左邊的酒一定要往右邊運。所以,把當前走過的村莊的絕對值加起來,再加上當前村莊的(可以是負數),即為簡單演算法。具體見代碼。

 1 #include <iostream> 2 #include <cmath> 3 #include <cstring> 4 #include <cstdio> 5 #include <cstdlib> 6 #include <algorithm> 7 using namespace std; 8 int a[1010101]; 9 int main()10 {11     int n;12     while(cin>>n)13     {14         if(n==0) break;15         for(int i=1;i<=n;i++) scanf("%d",&a[i]);16         int m=a[1],ans=0;17         for(int i=2;i<=n;i++)18         {19             ans+=abs(m);20             m+=a[i];21         }22         printf("%d\n",ans);23     }24     //system("pause");25     return 0;26 }
Gergovia的酒交易B805

 

Gergovia的酒交易B805(移動紙牌)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.