floyd后遍历下就好
代码
#include <iostream>
#include <cstring>
#include <cstdio>
#include <climits>
const int N = 110;
int map[N][N];
int n;
void floyd()
{
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if(map[i][k]!=-1&&map[k][j]!=-1)
{
if(map[i][j]==-1)
{
map[i][j] = map[i][k] + map[k][j];
}
else if(map[i][j]>map[i][k]+map[k][j])
{
map[i][j] = map[i][k]+map[k][j];
}
}
}
/////////////////////////////
int st=0 ,ans = INT_MAX;
for(int i=1;i<=n;i++)
{
int tans = 0;
bool flag = false;
for(int j=1;j<=n;j++)
{
if(i!=j)
{
if(map[i][j]==-1)
{
flag=true;
break;
}
else
{
if(map[i][j]>tans)
{
tans = map[i][j];
}
}
}
}
if(!flag&&ans>tans)
{
ans = tans;
st = i;
}
}
if(st==0)
{
printf("disjoint\n");
}
else
{
printf("%d %d\n",st,ans);
}
}
using namespace std;
int main()
{
while(scanf("%d",&n)!=EOF&&n!=0)
{
memset(map,255,sizeof(map));
for(int i=1;i<=n;i++)
{
int num;
scanf("%d",&num);
for(int j=1;j<=num;j++)
{
int v,cost;
scanf("%d%d",&v,&cost);
map[i][v] = cost;
}
}
floyd();
}
return 0;
}
#include <cstring>
#include <cstdio>
#include <climits>
const int N = 110;
int map[N][N];
int n;
void floyd()
{
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if(map[i][k]!=-1&&map[k][j]!=-1)
{
if(map[i][j]==-1)
{
map[i][j] = map[i][k] + map[k][j];
}
else if(map[i][j]>map[i][k]+map[k][j])
{
map[i][j] = map[i][k]+map[k][j];
}
}
}
/////////////////////////////
int st=0 ,ans = INT_MAX;
for(int i=1;i<=n;i++)
{
int tans = 0;
bool flag = false;
for(int j=1;j<=n;j++)
{
if(i!=j)
{
if(map[i][j]==-1)
{
flag=true;
break;
}
else
{
if(map[i][j]>tans)
{
tans = map[i][j];
}
}
}
}
if(!flag&&ans>tans)
{
ans = tans;
st = i;
}
}
if(st==0)
{
printf("disjoint\n");
}
else
{
printf("%d %d\n",st,ans);
}
}
using namespace std;
int main()
{
while(scanf("%d",&n)!=EOF&&n!=0)
{
memset(map,255,sizeof(map));
for(int i=1;i<=n;i++)
{
int num;
scanf("%d",&num);
for(int j=1;j<=num;j++)
{
int v,cost;
scanf("%d%d",&v,&cost);
map[i][v] = cost;
}
}
floyd();
}
return 0;
}