UVa Problem 10037 Bridge (過橋)

來源:互聯網
上載者:User
// Bridge (過橋)// PC/UVa IDs: 110403/10037, Popularity: B, Success rate: low Level: 3// Verdict: Accepted// Submission Date: 2011-05-22// UVa Run Time: 0.012s//// 著作權(C)2011,邱秋。metaphysis # yeah dot net//// 首先將所有過橋時間排序,以下為獲得最小過橋時間的演算法:// (1)過橋總人數為 1,該人的過橋時間即為最短過橋時間。// (2)過橋總人數為 2,過橋時間較大的人的過橋時間即為最短過橋時間。// (3)過橋總人數為 3,假設為A,B,C,則(AB),(A),(AC)策略和 (AC),(A),(AB)策略// 的時間相同,3人過橋時間之和為最短時間。// (4)過橋總人數大於3,假設最前面為A,B兩人,最後為Y,Z兩人,有兩種策略:(AB),(A),(YZ),// (B),(AB)和(AZ),(A),(AY),(A),(AB)。比較兩種策略那種過橋時間少就選那種,然後// 將總人數減去 2,若總人數仍大於 3,繼續該步驟直到剩下需要過橋的人數小於等於 3。可用遞迴或直接迭代實現。#include <iostream>#include <algorithm>using namespace std;#define MAXSIZE (1000 + 1)int shortest_time(int time[], int capacity){if (capacity == 1)return time[0];if (capacity == 2)return time[1];if (capacity == 3)return time[0] + time[1] + time[2];if (2 * time[1] < (time[0] + time[capacity - 2]))return time[0] + 2 * time[1] + time[capacity - 1] + shortest_time(time, capacity - 2);elsereturn 2 * time[0] + time[capacity - 2] + time[capacity - 1] + shortest_time(time, capacity - 2);}void bridge(int time[], int capacity){if (capacity == 1){cout << time[0] << "\n";return;}if (capacity == 2){cout << time[0] << " " << time[1] << "\n";return;}if (capacity == 3){cout << time[0] << " " << time[2] << "\n";cout << time[0] << "\n";cout << time[0] << " " << time[1] << "\n";return;}if (2 * time[1] < (time[0] + time[capacity - 2])){cout << time[0] << " " << time[1] << "\n";cout << time[0] << "\n";cout << time[capacity - 2] << " " << time[capacity - 1] << "\n";cout << time[1] << "\n";}else{cout << time[0] << " " << time[capacity - 1] << "\n";cout << time[0] << "\n";cout << time[0] << " " << time[capacity - 2] << "\n";cout << time[0] << "\n";}bridge(time, capacity - 2);}int main(int ac, char *av[]){int cases;int time[MAXSIZE];int capacity, index;cin >> cases;while (cases--){// 總人數。cin >> capacity;// 讀取每個人的過橋時間。index = 0;while (index < capacity)cin >> time[index++];// 將用時數組予以排序。sort(time, time + capacity);// 計算最短過橋時間,輸出過橋順序。cout << shortest_time(time, capacity) << endl;bridge(time, capacity);if (cases)cout << endl;}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.