M¹nh D¬ng Biªn So¹n
Bé M«n CÊu Tróc D÷ LiÖu
Gi¶i ThuËt 2012
§ª Sè 21 Trong Bé §Ò ¤n TËp
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
ifstream Tepvao("C:/cau truc du lieu/dethi/dothi21.in.txt");
ofstream Tepra("C:/cau truc du lieu/dethi/kequa21.out.txt");
int x[100];
/*
Thuat toan Djkstra tim duong di ngan nhat giua hai diem p q
*/
int kt(int i,int S[],int n)
{
for(int j=0;j<=n;j++)
if(S[j]==i)return 0;
return 1;
}
int dem=1;
void DFS(int i,int a[][100],int n,int k)
{
x[i]=1;
for(int j=1;j<=n;j++)
if(x[j]==0&&a[i][j]==1){if(j==k){dem=0;return;}
DFS(j,a,n,k);}
}
int KT(int i,int j,int n,int a[][100])
{
dem=1;
DFS(i,a,n,j);
if(dem==1)return 0;
return 1;
}
void Djkstra()
{
int W[100][100],S[100],P[100],D[100],X[100];
int n;
Tepvao>>n;
int a,b;
Trang 2Tepvao>>b;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
Tepvao>>W[i][j];
}
if(KT(a,b,n,W)==0){Tepra<<-1<<endl;return;} S[0]=a;
D[a]=0;
int nmin=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(W[i][j]>nmin)nmin=W[i][j];
nmin=nmin*n;
for(int i=1;i<=n;i++)
if(i!=a&&W[a][i]!=0)
{
D[i]=W[a][i];
P[i]=a;
}
else if(i!=a&&W[a][i]==0)
{
D[i]=0;
}
int min;
min=nmin;
for(int i=1;i<=n;i++)
if(i!=a&&D[i]<min&&D[i]!=0){min=D[i];X[1]=i;} int dem=1;
S[1]=X[1];
while(S[dem]!=b)
{
int XX=D[X[dem]];
for(int i=1;i<=n;i++)
if(kt(i,S,dem)==1&&W[X[dem]][i]!=0) {
if(D[i]==-1) {
D[i]=XX+W[X[dem]][i];
P[i]=X[dem];
} else if(D[i]>XX+W[X[dem]][i]) {
D[i]=XX+W[X[dem]][i];
P[i]=X[dem];
Trang 3} }
min=nmin;
for(int i=1;i<=n;i++) if(kt(i,S,dem)==1&&min>D[i]&&D[i]!=0) {X[dem+1]=i;min=D[i];}
dem=dem+1;
S[dem]=X[dem];
}
Tepra<<D[b]<<endl;
int XX;X[0]=b;
dem=0;XX=b;
while(XX!=a)
{
dem++;
XX=P[XX];
X[dem]=XX;
}
for(int i=dem;i>=0;i )
Tepra<<X[i]<<" ";
Tepra<<endl;
return ;
}
main()
{
Djkstra();
}