Forget the complexity of the n^3 as if the feeling is not good to do. Results n^31a ...
#include <cstdio> #include <algorithm> #include <iostream> #include <string.h> #include <map > #include <vector> #include <string> #include <queue>using namespace std; #define EPS 1e-9#define PI ACOs ( -1.0) #define N 1005#define inf 10000000map<string,int>mp;vector<int>g[n*2];vector<string> Ans;int stack[n*2],topans;int N, M;char s[n*2][20], tmp[2][20];int vis[n*2];bool bfs (int u) {memset (vis,0,sizeof vis); Vis[u] = -1;queue<int>q;for (int i = 0; i < g[u].size (); i++) Q.push (G[u][i]), vis[g[u][i]]=-1;int siz = -2;while (!q . empty ()) {u = Q.front (); Q.pop (); for (int i = 0; i < g[u].size (); i++) {int v = g[u][i]; if (vis[v]==-1) continue;vis[v]++; if (Siz<vis[v]) {siz = Vis[v];topans = 1; Stack[0] = V;} else if (Siz==vis[v]) {stack[topans++] = V;}}} if (siz<0) return false;ans.clear (); for (int i = 0; i < Topans; i++) Ans.push_back (S[stack[i]]); sort (Ans.begin (), Ans.end ()); for (int i = 0; i < ans.size (); i++) {cout << Ans[i];i==ans.Size () -1?puts (""):p rintf (""); return true;} int main () {int T, Cas = 1, I, J; scanf ("%d", &t), while (t--) {mp.clear (); scanf ("%d%d", &n,&m); for (i = 1; I <= 2*n; i++) g[i].clear (); int top = 0;while (n--) {scanf ("%s%s", tmp[0],tmp[1]), if (Mp.find (tmp[0]) ==mp.end ()) {mp[tmp[0]] = ++top;memcpy (S[top],tmp[0], sizeof tmp[0]); i = top;} else i = Mp.find (tmp[0])->second;if (Mp.find (tmp[1]) ==mp.end ()) {mp[tmp[1]] = ++top;memcpy (s[top],tmp[1],sizeof tmp [1]); j = Top;} else J = mp.find (tmp[1])->second; G[i].push_back (j); G[j].push_back (i);} printf ("Case%d:\n", cas++), while (m--) {scanf ("%s", tmp[0]), i = Mp.find (tmp[0])->second;if (BFS (i) ==false) puts ("-" );}} return 0;}