演算法導論答案 16.2-4
阿新 • • 發佈:2019-01-31
//16.2-4 #include <iostream> using namespace std; #define N 6 int x[N+1]={0,10,40,60,90,120,140},f[N+1]={0};//f用於標記某一站是否加油,x[i]表示第i個加油站距離起始點的距離 void Greedy_Select(int x[],int f[])//選擇在哪一個加油站停車 { int n=30;//郵箱滿的時候,能夠跑的英里數 for(int i=2;i<=N;++i) { if(x[i]>n)//如果起始點到某個加油站的距離大於汽車在郵箱滿的時候能夠走的公里數,則在前一站加油 { f[i-1]=1;//標記前一站需要加油 n=30; n=n+x[i-1];//改變當前的距離,因為在第i-1站已經加過油 } } } void Construct_Opitimal_Solution(int x[],int f[])//輸出需要在哪一站加油 { for(int i=1;i<=N;++i) { if(f[i]==1) cout<<"The gas station "<<i<<" is chosen! And its distance is "<<x[i]<<endl; } } void main() { Greedy_Select(x,f); Construct_Opitimal_Solution(x,f); }