using namespace std; int **matrix; int *min_d; int **parent; int *visit; int node = 0; int pathnum = 0; int minpathvalue = 0; int start_point = 0; int end_point = 0; int pathexist = 1; int *length; void build_matrix() { int temp; int num=0; queue Q; while(1) { if(scanf("%d",&temp)!=1)break; num++; Q.push(temp); } char start,end; scanf("%c",&start); start_point = start-65; getchar(); scanf("%c",&end); end_point = end-65; node = int(sqrt(float(num))); matrix = new int *[node]; for(int i=0;i<node;i++) { matrix[i] = new int [node]; for(int j=0;j<node;j++) { matrix[i][j] = Q.front(); Q.pop(); if(matrix[i][j] == 0) matrix[i][j] = 0x3fffffff; } }
} void dijkstra(int startpoint) { min_d = new int [node]; parent = new int *[node]; for(int i=0;i<node;i++){ parent[i]= new int [node]; for(int j=0;j<node;j++) { parent[i][j]=-1; } } visit = new int [node]; for (int i=0; i<node; i++) visit[i] = 0; for (int i=0; i<node; i++) min_d[i] = 1e9; min_d[start_point] = 0; for(int i = 0;i<node;i++) { parent[i][0]= i; } for (int i=0; i<node; i++) { int a = -1, b = -1, min = 1e9; for (int i=0; i<node; i++) if ( visit[i]!=1 && min_d[i] < min) { a = i; min = min_d[i]; } if (a == -1) break; visit[a] = 1; for (b=0; b<node; b++){ if (!visit[b] && min_d[a] + matrix[a][b] <= min_d[b]) { if(min_d[a]+matrix[a][b] < min_d[b]) { parent[b][0] = a; for(int i=1;i<node-1;i++) { parent[b][i]=-1; } } else { for(int j=1;j<node;j++) { if(parent[b][j]==-1)parent[b][j]=a;break; } } min_d[b] = min_d[a]+matrix[a][b] ; } } } } void If_exist(int endpoint) {
if(min_d[endpoint] == 1e9) { cout<<"沒有找到"<= 0 ; row_num--) for(int i = 0;i<length[row];i++) { calculate_path(startpoint,parent[endpoint][i],parent[endpoint][i]); } } } void other_path(int startpoint,int endpoint) { if(endpoint == startpoint) {return;} else minpathvalue = minpathvalue+matrix[(parent[endpoint][0])][endpoint]; other_path(startpoint,parent[endpoint][0]); } void printPath(char startpoint, char endpoint, int before[], int len,int row) {
if (endpoint == startpoint) {
printf("%c",startpoint+'A'); return ; } before[len] = endpoint; for (int i = 0 ; i 0) { for (int j = len - 1 ; j >= 0 ; --j) { } cout<<endl; } printPath( startpoint, parent[endpoint][i], before, len + 1, parent[endpoint][i]); } } int main() { freopen("DS4.txt","r",stdin); freopen("Ans4.txt","w",stdout); build_matrix(); dijkstra(start_point); if(If_exist) { length = new int [node]; for(int i = 0;i<node;i++) { length[i] = 0; for(int j = 0;j<node;j++) { if(parent[i][j]==-1)break; else { length[i] = length[i]+1; } } } calculate_path(start_point,end_point,end_point); cout<<pathnum<<endl; other_path(start_point,end_point); cout<<minpathvalue<<endl; int *before = new int [node]; printPath(start_point,end_point,before,0,end_point); } }
|