#include <stdio.h> #include <limits> #define LEN 10 int a[LEN][LEN],path[LEN][LEN]; int main() { int i,j,k,n,m; n=5,m=6; for(i=1;i<=5;i++) { for(j=1;j<=5;j++) if(i!=j) a[i][j]=std::numeric_limits<int>::max(),path[i][j]=i; } a[1][2]=2,a[2][1]=2; a[1][4]=1,a[4][1]=1; a[1][5]=2,a[5][1]=2; a[2][3]=4,a[3][2]=4; a[2][5]=1,a[5][2]=1; a[3][4]=3,a[4][3]=3; for(i=1;i<=5;i++) { for(j=1;j<=5;j++) { for(k=1;k<=5;k++) { if(a[j][i]!=std::numeric_limits<int>::max() && a[i][k]!=std::numeric_limits<int>::max() && a[j][k]>a[j][i]+a[i][k]) a[j][k]=a[j][i]+a[i][k],path[j][k ]=i; } } } for(i=1;i<=5;i++) { for(j=1;j<=5;j++) printf("%2d ",a[i][j]); printf("\n"); } int x,y,res; scanf("%d %d",&x,&y); printf("%d ",y); if(x==y) return 0; res=path[x][y]; while(res!=x) { printf("%d ",res); res=path[x][res]; } printf("%d ",x); return 0; }
#include<stdio.h> #include<limits> void update(int arr[5][5], int var[5][5]); void path(int var[5][5], int i, int j); void main(){ int arr[5][5] = { 0 }; int var[5][5] = { 0 }; arr[0][0] = 0; arr[1][0] = 2; arr[1][1] = 0; arr[2][0] = std::numeric_limits<int>::max(); arr[2][1] = 4; arr[2][2] = 0; arr[3][0] = 1; arr[3][1] = std::numeric_limits<int>::max(); arr[3][2] = 3; arr[3][3] = 0; arr[4][0] = 2; arr[4][1] = 1; arr[4][2] = std::numeric_limits<int>::max(); arr[4][3] = std::numeric_limits<int>::max(); arr[4][4] = 0; update(arr, var); path(var, 4, 1); } void update(int arr[5][5], int var[5][5]){ int temp1, temp2, temp3, temp4; int i, j, k; for (k = 0; k < 5; k++){ for (i = 1; i < 5; i++){ for (j = 0; j < i; j++){ if (k == j){ continue; } if (k == i){ continue; } if (i> k){ temp1 = i; temp2 = k; } else{ temp1 = k; temp2 = i; } if (j > k){ temp3 = j; temp4 = k; } else{ temp3 = k; temp4 = j; } if (arr[temp1][temp2] == std::numeric_limits<int>::max() || arr[temp3][temp4] == std::numeric_limits<int>::max()){ continue; } if (arr[i][j] > arr[temp1][temp2] + arr[temp3][temp4]){ var[i][j] = k; arr[i][j] = arr[temp1][temp2] + arr[temp3][temp4]; } } } } } void path(int var[5][5], int i, int j){ printf("%c", 'A' + i); int temp = var[i][j]; int temp1, temp2; if (temp > i){ temp1 = i; temp2 = temp; } else{ temp1 = temp; temp2 = i; } while (temp != var[temp2][temp1]){ printf("%c", 'A' + temp); temp = var[i][temp]; if (temp > i){ temp1 = i; temp2 = temp; } else{ temp1 = temp; temp2 = i; } } printf("%c", 'A' + j); }