This question has always been TLE and timed out. At first I thought it was an algorithm problem. Later I realized it was an input problem. It was too difficult.
This question can be solved using BFs, and there is no problem with Floyd.
However, you must note that when you enter a word pair, the Terminator is divided into two types. One is that the null behavior ends in the middle of several consecutive input groups, and the last group of data ends with an EOF.
Note: Some of the comments are Floyd, but it is normal to solve the problem with BFs.
Code:
#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <map>#include <queue>using namespace std;const int N = 300;const int INF = 1000000;int T, id;int g[N][N], d[N];map <string, int> mp;string s1, s2, s[N];int bfs( int st, int en ) { queue< int > q; q.push(st); for ( int i = 0; i <= id; ++i ) d[i] = INF; d[st] = 0; while ( !q.empty() ) { int u = q.front(); q.pop(); if ( u == en ) break; for ( int i = 0; i < id; ++i ) if ( g[u][i] && d[i] > d[u] + 1 ) { q.push(i); d[i] = d[u]+1; } } return d[en];} int main(){ bool f = false; scanf("%d", &T); getchar(); while ( T-- ) { if ( f ) cout << endl; f = true, id = 0; //for ( int i = 0; i < N; ++i ) for ( int j = i; j < N; ++j ) g[i][j] = g[j][i] = INF; memset(g, 0, sizeof(g)); mp.clear(); while ( cin >> s[id] && s[id] != "*" ){ if ( !mp[s[id]] ) { mp[s[id]] = id; for ( int i = 0; i < id; ++i ) if ( s[id].size() == s[i].size() ) { int num = 0; for ( int k = 0; k < s[id].size() && num < 2; ++k ) if ( s[id][k] != s[i][k] ) num++; if ( num == 1 ) g[id][i] = g[i][id] = 1; } id++; } } //for ( int k = 0; k < id; ++k ) for ( int i = 0; i < id; ++i ) for ( int j = 0; j < id; ++j ) // if ( g[i][k] + g[k][j] < g[i][j] ) g[i][j] = g[i][k] + g[k][j]; char ch; getchar(); while ( ( ch = getchar() ) != 0xa && ch != EOF ) { cin >> s1; s2.clear(); s2 += ch; s2 += s1; cin >> s1; getchar(); int u = mp[s2], v = mp[s1]; cout << s2 << " " << s1 << " " << bfs( u, v ) << endl; } }}