比较水的全源最短路,Floyd一次就OK了,给一个加固城堡,找出所有点中离加固城堡最远的点,加固之,然后在所有未加固的城堡中找离加固城堡最远的点,依次进行
#include<cstdio>
#include<vector>
#include<climits>
#include<cstring>
using namespace std;
int main()
{
puts("Program 8 by team X");
int n, m, map[26][26], prev[26][26];
char b[2], s[2], t[2];
scanf("%d %s %d", &n, b, &m);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
map[i][j] = i == j ? 0 : INT_MAX;
while (scanf("%s %s", s, t) != EOF)
map[s[0] - 'A'][t[0] - 'A'] = map[t[0] - 'A'][s[0] - 'A'] = 1;
memcpy(prev, map, sizeof(map));
for (int k = 0; k < n; k++)
{
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (prev[i][k] != INT_MAX && prev[k][j] != INT_MAX
&& prev[i][k] + prev[k][j] < prev[i][j])
map[i][j] = prev[i][k] + prev[k][j];
memcpy(prev, map, sizeof(map));
}
vector<int> V;
V.push_back(b[0] - 'A');
bool flag[26];
memset(flag, 0, sizeof(flag));
flag[b[0] - 'A'] = true;
putchar(b[0]);
while (--m)
{
putchar(' ');
int maxd = 0, curr;
for (int i = 0; i < n; i++)
{
int mind = INT_MAX;
if (!flag[i])
{
for (size_t t = 0; t < V.size(); t++)
if (map[i][V[t]] < mind)
mind = map[i][V[t]];
if (mind > maxd)
{
maxd = mind;
curr = i;
}
}
}
V.push_back(curr);
flag[curr] = true;
putchar(curr + 'A');
}
puts("\nEnd of program 8 by team X");
return 0;
}