此题用深搜很快就解决,我用宽度搜索和优先队列仅仅是为了练习他们的用法;深搜法在注释内;
1 #include<iostream> 2 #include<cstring> 3 #include<queue> 4 using namespace std; 5 const int N=1000; 6 int map[N][N]; 7 int vis[N][N]; 8 int n; 9 struct Node 10 { 11 int x,y,value; 12 friend bool operator<(Node a,Node b) 13 {return a.value<b.value; 14 } 15 16 }; 17 /* 18 int dfs(int i,int j) 19 { 20 if(i==n)return map[i][j]; 21 int num1=map[i][j]+dfs(i+1,j); 22 int num2=map[i][j]+dfs(i+1,j+1); 23 return num1>num2?num1:num2; 24 } 25 */ 26 int dfs(int x,int y) 27 { 28 priority_queue<Node>Q; 29 queue<Node>q; 30 Node a; 31 Node b; 32 a.x=x; 33 a.y=y; 34 a.value=map[x][y]; 35 q.push(a) ; 36 Q.push(a); 37 38 while(!Q.empty()) 39 { 40 a=q.front(); 41 q.pop(); 42 if(a.x==n)return Q.top().value; 43 for(int i=0;i<=1;i++) 44 { 45 b.x=a.x+1; 46 b.y=a.y+i; 47 b.value=a.value+map[b.x][b.y]; 48 if(vis[b.x][b.y]<b.value) 49 { 50 vis[b.x][b.y]=b.value; 51 q.push(b); 52 Q.push(b); 53 } 54 } 55 } 56 return 0; 57 } 58 int main() 59 { 60 61 while(cin>>n) 62 { 63 for(int i=1;i<=n;i++) 64 for(int j=1;j<=i;j++) 65 { 66 cin>>map[i][j]; 67 vis[i][j]=map[i][j]; 68 } 69 cout<<endl<<dfs(1,1)<<endl; 70 } 71 return 0; 72 }