N個人要從河的一側到另一次 一個船最多做2個人 這個船的速度受慢的人的影響。
輸入一堆數,爲每個人 的時間,怎麼規劃划船的總時間最少?
- #include <iostream>
- #include <list>
- #include <algorithm>
- using namespace std;
- void input();
- void sortlist();
- void show();
- void solution(int sel);
- list<int> timelistA,timelistB;
- int time;
- void main()
- {
- input();
- sortlist();
- solution(0);
- cout<<endl<<"總用時"<<time<<"秒"<<endl<<endl;
- }
- void solution(int sel)
- {
- timelistA.sort();
- timelistB.sort();
- if (timelistA.size()==0)
- {
- return;
- }
- if(0==sel) // 左->右
- {
- if (timelistA.size()>1)
- {
- list<int >::iterator a=timelistA.begin();
- list<int >::iterator b=timelistA.begin();b++;
- timelistB.push_back(*a);
- cout<<*a;
- timelistA.erase(a);
- cout<<" "<<*b<<"過去"<<endl;
- timelistB.push_back(*b);
- time+=*b;
- timelistA.erase(b);
- }
- else
- {
- cout<<timelistA.front()<<" "<<"過去"<<endl;
- timelistB.push_back(timelistA.front());
- time+=timelistA.front();
- timelistA.erase(timelistA.begin());
- }
- solution(1);
- }
- else if(1==sel) //右->左 回來
- {
- cout<<timelistB.front()<<" 回來"<<endl;
- timelistA.push_back(timelistB.front());
- time+=timelistB.front();
- timelistB.erase(timelistB.begin());
- solution(2);
- }
- else if (2==sel)//左->右
- {
- list<int >::iterator a=timelistA.end();
- a--;
- list<int >::iterator b=a;
- b--;
- timelistB.push_back(*a);
- timelistB.push_back(*b);
- cout<<*a<<" ";
- cout<<*b<<" 過去"<<endl;
- time+=*a;
- timelistA.erase(a);
- timelistA.erase(b);
- solution(3);
- }
- else if (3==sel)
- {
- cout<<timelistB.front()<<" 過來"<<endl;
- time+=timelistB.front();
- timelistA.push_back(timelistB.front());
- timelistB.erase(timelistB.begin());
- solution(0);
- }
- }
- void input()
- {
- cout<<"input every one :"<<endl;
- while(1)
- {
- int a;
- cin>>a;
- timelistA.push_back(a);
- if (getchar()=='\n')
- {
- break;
- }
- }
- cout<<endl;
- }
- void sortlist()
- {
- timelistA.sort();
- }
- void show()
- {
- list<int>::iterator a=timelistA.begin();
- for(;a!=timelistA.end();++a)
- cout<<*a<<"\t";
- }