三辆车在三个点作为状态,位置依次增大作为状态标识,状态函数标识当前状态距离最终状态还需要行驶的距离。
#include<iostream>
using namespace std;
int n;
int graph[31][31];
int flag[31][31][31];
int D(int a,int b,int c){
int tmp = 99999;
if(c == n) return 0;
if(!flag[b][c][c+1])flag[b][c][c+1] = D(b,c,c+1);
if(!flag[a][c][c+1])flag[a][c][c+1] = D(a,c,c+1);
if(!flag[a][b][c+1])flag[a][b][c+1] = D(a,b,c+1);
if(tmp>flag[b][c][c+1]+graph[a][c+1])tmp = flag[b][c][c+1]+graph[a][c+1];
if(tmp>flag[a][c][c+1]+graph[b][c+1])tmp = flag[a][c][c+1]+graph[b][c+1];
if(tmp>flag[a][b][c+1]+graph[c][c+1])tmp = flag[a][b][c+1]+graph[c][c+1];
return tmp;
}
int main(){
int i,j,t;
cin >> t;
while(t--){
cin >> n;
memset(graph,0,sizeof(int)*31*31);
memset(flag,0,sizeof(int)*31*31*31);
for(i=1;i<=n-1;i++){
for(j=i+1;j<=n;j++){
cin >> graph[i][j];
graph[j][i] = graph[i][j];
}
}
cout << D(1,1,1)<<endl;
}
}