#include #define N_MAX 100 #define M_MAX 5000 typedef struct Edge { struct Edge *next; int v; unsigned int label; } edge; void DFS_naive(edge* adj[], int X, int Y, int Z, int u, int flag[], int* tmp, int* ans) { if (flag[u] != 0) { if (u == X && flag[Y] != 0 && flag[Z] != 0) *ans = *tmp; return; } else flag[u] = 1; edge *p; (*tmp)++; if (*tmp < *ans) for (p = adj[u]; p != NULL; p = p->next) DFS_naive(adj, X, Y, Z, p->v, flag, tmp, ans); (*tmp)--; flag[u] = 0; } // Naive solution int naive(int N, int M, int X, int Y, int Z, int A[], int B[]) { static int i, u, w, adj_mat[N_MAX + 1][N_MAX + 1]; static edge *adj[N_MAX + 1], e[M_MAX * 2], *p; for (u = 1; u <= N; u++) for (w = u + 1; w <= N; w++) adj_mat[u][w] = 0; for (i = 1; i <= M; i++) { u = A[i]; w = B[i]; adj_mat[u][w] = 1; } for (u = 1; u <= N; u++) adj[u] = NULL; for (u = 1, i = 0; u <= N; u++) { for (w = u + 1; w <= N; w++) { if (adj_mat[u][w] != 0) continue; e[i].v = w; e[i].next = adj[u]; adj[u] = &(e[i++]); e[i].v = u; e[i].next = adj[w]; adj[w] = &(e[i++]); } } static int flag[N_MAX + 1] = {}, q[N_MAX + 1], head, tail; // Y--Z path? flag[X] = 1; flag[Y] = 1; q[0] = X; q[1] = Y; for (head = 1, tail = 2; head < tail; head++) { u = q[head]; for (p = adj[u]; p != NULL; p = p->next) { w = p->v; if (flag[w] == 0) { flag[w] = 1; q[tail++] = w; } } } if (flag[Z] == 0) { for (head = 0; head < tail; head++) flag[q[head]] = 0; return -1; } else for (head = 0; head < tail; head++) flag[q[head]] = 0; // Z--X path? flag[Y] = 1; flag[Z] = 1; q[0] = Y; q[1] = Z; for (head = 1, tail = 2; head < tail; head++) { u = q[head]; for (p = adj[u]; p != NULL; p = p->next) { w = p->v; if (flag[w] == 0) { flag[w] = 1; q[tail++] = w; } } } if (flag[X] == 0) { for (head = 0; head < tail; head++) flag[q[head]] = 0; return -1; } else for (head = 0; head < tail; head++) flag[q[head]] = 0; // X--Y path? flag[Z] = 1; flag[X] = 1; q[0] = Z; q[1] = X; for (head = 1, tail = 2; head < tail; head++) { u = q[head]; for (p = adj[u]; p != NULL; p = p->next) { w = p->v; if (flag[w] == 0) { flag[w] = 1; q[tail++] = w; } } } if (flag[Y] == 0) { for (head = 0; head < tail; head++) flag[q[head]] = 0; return -1; } else for (head = 0; head < tail; head++) flag[q[head]] = 0; // DFS int ans = N + 1, tmp = 0; DFS_naive(adj, X, Y, Z, X, flag, &tmp, &ans); if (ans > N) return -1; else return ans; } int main() { int i, N, M, X, Y, Z, A[M_MAX + 1], B[M_MAX + 1]; scanf("%d %d", &N, &M); scanf("%d %d %d", &X, &Y, &Z); for (i = 1; i <= M; i++) scanf("%d %d", &(A[i]), &(B[i])); printf("%d\n", naive(N, M, X, Y, Z, A, B)); fflush(stdout); return 0; }