用了dij写,超时了,不过好歹解决了WA。明天尝试用dfs写一遍。
把dij的代码记录一下
#include<iostream>
#include<cstdio>
using namespace std;
#define MAXINT 0x3f3f3f3f
struct p{
char name[12];
}person[1002];
int n,rea[1002][1002];
int search(char a[]){
for (int i = 1; i <= n; i++){
if (strcmp(a, person[i].name) == 0){
return i;
}
}
return 0;
}
int dijkstra(int v){
int dist[1002];
bool s[1002];
int i, j;
for (i = 1; i <= n; i++){
dist[i] = rea[v][i];
s[i] = false;
}
dist[v] = 0;
s[v] = true;
for (j = 2; j <= n; j++){
int min = MAXINT;
int u = v;
for (i = 1; i <= n; i++){
if ((!s[i]) && dist[i] < min){
u = i;
min = dist[i];
}
}
s[u] = true;
for (i = 1; i <= n; i++){
if ((!s[i]) && rea[u][i] < MAXINT){
if (dist[u] + rea[u][i] < dist[i]){
dist[i] = dist[u] + rea[u][i];
}
}
}
}
int maxdist = -1;
for (i = 1; i <= n; i++){
if (dist[i] >= MAXINT){
return -1;
}
if (dist[i] > 0 && dist[i]<MAXINT && dist[i]>maxdist){
maxdist = dist[i];
}
}
return maxdist;
}
int main(){
freopen("TestDate.txt", "r", stdin);
int i,j,m,temp,max;
char tname[12];
while (cin >> n&&n){
memset(rea,0x3f,sizeof(rea));
for (i = 1; i <= n; i++){
cin >> person[i].name;
}
cin >> m;
while (m--){
cin >> tname;
i = search(tname);
cin >> tname;
j = search(tname);
rea[i][j] = rea[j][i] = 1;
}
max = -1000;
for (i = 1; i <= n; i++){
temp = dijkstra(i);
if (temp == -1){
cout << -1 << endl;
break;
}
if (temp > max){
max = temp;
}
}
if (temp != -1){
cout << max << endl;
}
}
return 0;
}