简单的模板应用,就是求图中各个点中,每个点到其余各点最大距离的最小值。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define maxn 110
#define maxint 999999
int mapp[maxn][maxn];//the map of the problem
int ans[maxn];//the longest distance of every point
int dist[maxn];//the distance between the v and the other point
int n;
int Dijsktra(int v)
{
bool s[maxn];
int i,j;
for(i=1;i<=n;i++)
{
dist[i]=mapp[v][i];
s[i]=false;
}
dist[v]=0;
s[v]=true;
for(i=2;i<=n;i++)
{
int tmp=maxint;
int u=v;
for(j=1;j<=n;j++)
if(!s[j]&&dist[j]<tmp)
{
u=j;tmp=dist[j];
}
s[u]=1;
for(j=1;j<=n;j++)
if(!s[j]&&mapp[u][j]<maxn)
{
int newdist=dist[u]+mapp[u][j];
if(newdist<dist[j])
{
dist[j]=newdist;
}
}
}
int max=0;
for(i=1;i<=n;i++){
if(dist[i]>max)
max=dist[i];
}
return max;
}
int main()
{
int m,i,j,a,b,min,f;
while(scanf("%d",&n)!=EOF)
{
if(n==0) break;
memset(mapp,maxint,sizeof(mapp));
for(j=1;j<=n;j++)
{
scanf("%d",&m);
for(i=1;i<=m;i++)
{
scanf("%d%d",&a,&b);
mapp[j][a]=b;
}
}
for(i=1;i<=n;i++)
{ans[i]=Dijsktra(i);}
min=maxint;
for(i=1;i<=n;i++)
if(ans[i]<min)
{
min=ans[i];
f=i;
}
printf("%d %d\n",f,min);
}
return 0;
}
看了别人的代码,才发现这题的数据好弱啊,我都没有考虑不通的情况都过了。
#include <iostream> #include <cstring> using namespace std; const int MAX_VERTEX=128; const int MAX_EDGE_WEIGHT=100000000; int nv;//the number of vertex int gam[MAX_VERTEX][MAX_VERTEX];//the map of the problem int spd[MAX_VERTEX];//the distance between source point and the destination point int asd[MAX_VERTEX];//whether the point is explored int ansperson,anstime; int main() { int n,p,t,i,j,k; while(cin>>nv&&nv!=0) { for(i=1;i<=nv;i++) for(j=1;j<=nv;j++) gam[i][j]=MAX_EDGE_WEIGHT; for(i=1;i<=nv;i++) { cin>>n; for(j=1;j<=n;j++) { cin>>p>>t;gam[i][p]=t; } } ansperson=-1;anstime=MAX_EDGE_WEIGHT; for(k=1;k<=nv;k++) { for(i=1;i<=nv;i++) { if(i==k) asd[i]=1; else asd[i]=0; spd[i]=gam[k][i]; } for(i=1;i<=nv-2;i++) { int w=MAX_EDGE_WEIGHT,m=k; for(j=1;j<=nv;j++) { if(asd[j]==0&&w>spd[j]) { w=spd[j];m=j; } } if(m!=k) asd[m]=1; else break; for(j=1;j<=nv;j++) { if(asd[j]==0&&spd[j]>spd[m]+gam[m][j]) spd[j]=spd[m]+gam[m][j]; } } int time=0; for(i=1;i<=nv;i++) if(i!=k&&time<spd[i]) time=spd[i]; if(anstime>time) { ansperson=k;anstime=time; } } if(anstime!=MAX_EDGE_WEIGHT) cout<<ansperson<<' '<<anstime<<endl; else cout<<"disjoint"<<endl; } return 0; }