// Arup Guha
// 8/17/2014
// Solution to 2014 UCF Locals Problem: Faster Microwaving

import java.util.*;
import java.io.*;

public class microwave {

	// No optimal answer will exceed 30 minutes...
	final public static int MAX = 1800;
	final public static double EPSILON = 1e-8;
	public static int[] bestTimes;
	public static int[] bestKeys;

	public static void main(String[] args) throws Exception {

		// Precompute best touch times for each second.
		fillBest();

		Scanner stdin = new Scanner(new File("microwave.in"));
		int numCases = stdin.nextInt();

		// Process each case.
		for (int loop=1; loop<=numCases; loop++) {

			// Read in data.
			StringTokenizer tok = new StringTokenizer(stdin.next(),":");
			int min = Integer.parseInt(tok.nextToken());
			int sec = Integer.parseInt(tok.nextToken());
			int totSec = 60*min + sec;
			int perc = stdin.nextInt();

			int start = (int)(totSec - perc*totSec/100.0 + 1 - EPSILON);
			int end = (int)(totSec + perc*totSec/100.0 + EPSILON);

			// Look for best...
			int ans = start, presses = bestTimes[start];
			for (int t=start+1; t<=end; t++) {

				// Criteria for being a better combination.
				if (bestTimes[t] < presses || (bestTimes[t] == presses && Math.abs(t-totSec) < Math.abs(ans-totSec))) {
					presses = bestTimes[t];
					ans = t;
				}
			}

			// Result.
			System.out.println("Case #"+loop+": "+bestKeys[ans]);
		}
		stdin.close();
	}

	public static void fillBest() {

		bestTimes = new int[MAX];
		bestKeys = new int[MAX];

		// Fill in answers for each.
		for (int i=0; i<MAX; i++) {

			// Can always put in time regularly.
			bestKeys[i] = (i/60)*100 + (i%60);
			bestTimes[i] = getBestTime(bestKeys[i]);

			// See if we can add 60 to the seconds...
			if (i%60 < 40 && i > 59) {
				int altKeys = (i/60-1)*100 + (i%60 + 60);
				int altTime = getBestTime(altKeys);

				// This way is better.
				if (altTime < bestTimes[i]) {
					bestKeys[i] = altKeys;
					bestTimes[i] = altTime;
				}
			}
		}
	}

	// Returns the number of moments for pressing myTime.
	public static int getBestTime(int myTime) {

		int ans = 0, curDigit = -1;
		while (myTime > 0) {

			// Peel off digits from the end...this works also.
			int newDigit = myTime%10;

			// Had a switch, add one.
			if (curDigit >= 0 && curDigit != newDigit)
				ans++;

			// Count pressing the number and move on.
			ans++;
			curDigit = newDigit;
			myTime /= 10;
		}

		return ans;
	}
}