import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class search { static int[][] paths; public static void main(String[] args) { Scanner in = new Scanner(System.in); int sites, officers, pathnum; while ((sites = in.nextInt()) != 0) { officers = in.nextInt(); pathnum = in.nextInt(); paths = new int[sites][sites]; for (int i = 0; i < sites; i++) { for (int j = 0; j < sites; j++) { paths[i][j] = Integer.MAX_VALUE / 3; } } for (int i = 0; i < pathnum; i++) { String path = in.next(); paths[path.charAt(0) - 'A'][path.charAt(1) - 'A'] = 1; paths[path.charAt(1) - 'A'][path.charAt(0) - 'A'] = 1; } for (int k = 0; k < sites; k++) { for (int i = 0; i < sites; i++) { for (int j = 0; j < sites; j++) { int cur = paths[i][j]; int nuu = paths[i][k] + paths[j][k]; if (nuu < cur) paths[i][j] = nuu; } } } int[] locs = new int[officers]; for (int i = 0; i < officers; i++) locs[i] = 0; Set visited = new TreeSet(); visited.add(0); int[] times = new int[officers]; while (visited.size() < sites) { for (int i = 0; i < officers; i++) { int closest = getClosest(paths, locs[i], visited); if (closest == 9001) closest = getClosest2(paths, locs[i]); times[i] += paths[locs[i]][closest]; locs[i] = closest; visited.add(closest); } } int min = 9999; for (int i = 0; i < officers; i++) { if (times[i] < min) min = times[i]; } System.out.println(min); } } public static int getClosest(int[][] map, int start, Set invalid) { int min = 9001; int spot = 9001; for (int i = 0; i < map[0].length; i++) { if (invalid.contains(i)) continue; if (map[start][i] < min) { min = map[start][i]; spot = i; } } return spot; } public static int getClosest2(int[][] map, int start) { int min = 9002; int spot = 9002; for (int i = 0; i < map[0].length; i++) { if (map[start][i] < min) { min = map[start][i]; spot = i; } } return spot; } }