多段圖問題_動態規划法


先簡單敘述一下動態規划的步驟

 問題和思路

 

 

代碼如下

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int cost[10]; 4 int path[10]; 5 int array1[10][10]; 6 int main() 7 { 8 memset(cost,0,sizeof(cost)); 9 memset(path,0,sizeof(path)); 10 memset(array1,0,sizeof(array1)); 11 cout << "請輸入多段圖的邊數" << endl; 12 int m;//18 13 cin >> m; 14 cout << "請依次輸入多段圖的起點終點和路徑長度" << endl; 15 int start; 16 int stop; 17 int length; 18 for(int i=0;i<18;i++){ 19 cin >> start >> stop >> length; 20 array1[start][stop]=length; 21  } 22 for(int i=8;i>=0;i--){ 23 cost[i]=9999; 24 for(int j=i;j<10;j++){ 25 if(array1[i][j]!=0){//等於零表示之間沒有路 26 if(array1[i][j]+cost[j]<cost[i]){//此時找到一條更短的路 27 path[i]=j;//更新path[i] 28 cost[i]= array1[i][j]+cost[j];//更新從該節點出發的最短路徑 29  } 30  } 31  } 32  } 33 cout << "最短路徑長度是" << cost[0]; 34 cout <<endl; 35 cout << "最短路徑為"<< endl; 36 int i=0; 37 cout << "0--->"; 38 while(true){ 39 cout << path[i]; 40 i=path[i]; 41 if(i==9){ 42 break; 43  } 44 cout << "--->" ; 45  } 46 return 0; 47 }

運行結果如下

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM