分析:也是经典的单源最短路径问题,算法有多种,我这里用Bellman-Ford主要是练练。
Code
#include <iostream>
#include <iomanip>
using namespace std;
#define infinity 1000000
#define max_vertexes 20
typedef int Graph[max_vertexes][max_vertexes];
Graph G;
bool Input()
{
int n;
memset(G,0,sizeof(G));
for(int i=0;i<19;++i)
{
if(!(cin>>n))
return false;
int t;
for(int j=0;j<n;++j)
{
cin>>t;
G[i][t-1] = 1;
G[t-1][i] = 1;
}
}
return true;
}
int Bellman_ford(int n,int s,int t)
{
int i,j,k,d[max_vertexes];
for(i=0;i<n;++i)
d[i] = infinity;
d[s] = 0;
for(k=1;k<n;++k)
for(i=0;i<n;++i)
for(j=0;j<n;++j)
if(G[i][j]>0 && d[j]>d[i]+G[i][j])
d[j] = d[i] + G[i][j];
return d[t];
}
int main()
{
int t=1;
while(Input())
{
cout<<"Test Set #"<<t++<<endl;
int n,s,t,min;
cin>>n;
for(int i=0;i<n;++i)
{
cin>>s>>t;
min = Bellman_ford(20,s-1,t-1);
cout<<s<<" to "<<t<<": "<<min<<endl;
}
cout<<endl;
}
return 0;
}