也没啥好说的,纯粹给自己复习下算法,赤裸裸的Floyd最短路。
#include <iostream>
using namespace std;
#define MAXVALUE 1<<29
int main()
{
const int nNumber=20;
int graphMat[nNumber+1][nNumber+1];
int firstN;
int nTest=0;
while(cin>>firstN)
{
nTest++;
//Initialize the matrix
for(int i=1;i<=nNumber;i++)
for(int j=1;j<=nNumber;j++)
{
graphMat[i][j]=MAXVALUE;
}
for(int i=1;i<=nNumber;i++)
{
graphMat[i][i]=0;
}
int neighbor;
for(int ith=0;ith<firstN;ith++)
{
cin>>neighbor;
graphMat[1][neighbor]=graphMat[neighbor][1]=1;
}
int ithNeighbor;
for(int k=2;k<=19;k++)
{
cin>>ithNeighbor;
for(int ith=0;ith<ithNeighbor;ith++)
{
cin>>neighbor;
graphMat[k][neighbor]=graphMat[neighbor][k]=1;
}
}
for(int k=1;k<=nNumber;k++)
{
for(int i=1;i<=nNumber;i++)
for(int j=1;j<=nNumber;j++)
{
if(graphMat[i][j]>graphMat[i][k]+graphMat[k][j])
{
graphMat[i][j]=graphMat[i][k]+graphMat[k][j];
}
}
}
int nQuestion,nS,nE;
cin>>nQuestion;
cout<<"Test Set #"<<nTest<<endl;
while(nQuestion>0)
{
nQuestion--;
cin>>nS>>nE;
//1 to 20:
cout<<nS<<" to "<<nE<<": "<<graphMat[nS][nE]<<endl;
}
cout<<endl;
}
return 0;
}