Problem:
Problem C:
Stopped Watches
In the middle of Tyrrhenian Sea, there is a small volcanic island called Chronus. The island
is now uninhabited but it used to be a civilized island. Some historical records imply that the
island was annihilated by an eruption of a volcano about 800 years ago and that most of the
people in the island were killed by pyroclastic flows caused by the volcanic activity. In 2003, a
European team of archaeologists launched an excavation project in Chronus Island. Since then,
the project has provided many significant historic insights. In particular the discovery made
in the summer of 2008 astonished the world: the project team excavated several mechanical
watches worn by the victims of the disaster. This indicates that people in Chronus Island had
such a highly advanced manufacturing technology.
Shortly after the excavation of the watches, archaeologists in the team tried to identify what
time of the day the disaster happened, but it was not successful due to several difficulties. First,
the extraordinary heat of pyroclastic flows severely damaged the watches and took away the
letters and numbers printed on them. Second, every watch has a perfect round form and one
cannot tell where the top of the watch is. Lastly, though every watch has three hands, they
have a completely identical look and therefore one cannot tell which is the hour, the minute,
or the second (It is a mystery how the people in Chronus Island were distinguishing the three hands. Some archaeologists
guess that the hands might be painted with different colors, but this is only a hypothesis, as the paint was lost
by the heat.
). This means that we cannot decide the time indicated by a watch uniquely;
there can be a number of candidates. We have to consider different rotations of the watch.
Furthermore, since there are several possible interpretations of hands, we have also to consider
all the permutations of hands.
You are an information archaeologist invited to the project team and are asked to induce the
most plausible time interval within which the disaster happened, from the set of excavated
watches.
In what follows, we express a time modulo 12 hours. We write a time by the notation
hh
:
mm
:
ss
,
where
hh
,
mm
, and
ss
stand for the hour (
hh
= 00, 01, 02, . . . , 11), the minute (
mm
= 00,
01, 02, . . . , 59), and the second (
ss
= 00, 01, 02, . . . , 59), respectively. The time starts from
00:00:00 and counts up every second 00:00:00, 00:00:01, 00:00:02, . . ., but it reverts to 00:00:00
every 12 hours.
The watches in Chronus Island obey the following conventions of modern analog watches.
A watch has three hands, i.e. the hour hand, the minute hand, and the second hand,
though they look identical as mentioned above.
Every hand ticks 6 degrees clockwise in a discrete manner. That is, no hand stays between
ticks, and each hand returns to the same position every 60 ticks.
The second hand ticks every second.
The minute hand ticks every 60 seconds.
The hour ha
...(truncated)

Submitted solutions:

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

const int D = 12 * 60 * 60;
int id[61][61][61] = {};

void init() {
    for(int a : rep(60)) for(int b : rep(60)) for(int c : rep(60)) id[a][b][c] = -1;
    int h = 0, m = 0, s = 0;
    for(int i : rep(D)) {
        id[h][m][s] = i;
        s++;
        if(s == 60) {
            m++;
            s = 0;
            if(m % 12 == 0) {
                h++;
                if(m == 60) m = 0;
            }
        }
    }
}

void solve(int n) {
    vector<vector<int>> a = in(n, 3);
    for(int i : rep(n)) sort(a[i]);

    const int INF = 1e9;
    pair<int,int> ans = {INF, INF};

    for(int si : rep(n)) {
        do {
            for(int add : rep(60)) {
                int sh = (a[si][0] + add) % 60;
                int sm = (a[si][1] + add) % 60;
                int ss = (a[si][2] + add) % 60;
                const int s = id[sh][sm][ss];
                if(s == -1) continue;
                int u = s;

                bool ok = [&] {
                    for(int ti : rep(n)) if(ti != si) {
                        int t_min = INF;
                        do {
                            for(int add_in : rep(60)) {
                                int th = (a[ti][0] + add_in) % 60;
                                int tm = (a[ti][1] + add_in) % 60;
                                int ts = (a[ti][2] + add_in) % 60;
                                const int t = id[th][tm][ts];
                                if(t == -1) continue;
                                if(s <= t) chmin(t_min, t);
                            }
                        } while(next_permutation(a[ti].begin(), a[ti].end()));
                        if(t_min == INF) return false;
                        chmax(u, t_min);
                    }
                    return true;
                }();

                if(ok) chmin(ans, make_pair(u - s, s));
            }
        } while(next_permutation(a[si].begin(), a[si].end()));
    }

    const int fr = ans.second;
    const int to = ans.second + ans.first;
    printf("%02d:%02d:%02d %02d:%02d:%02d\n", (fr/60)/60, (fr/60)%60, fr%60, (to/60)/60, (to/60)%60, to%60);
}

int main() {
    init();
    while(true) {
        int n = in();
        if(n == 0) break;
        solve(n);
    }
}
accuracy: 1
time_ms: 50
memory_kb: 4412
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, s, t) for (int i = (int)(s); i < (int)(t); ++i)
#define revrep(i, t, s) for (int i = (int)(t)-1; i >= (int)(s); --i)
#define all(x) begin(x), end(x)
template <typename T> bool chmax(T& a, const T& b) { return a < b ? (a = b, 1) : 0; }
template <typename T> bool chmin(T& a, const T& b) { return a > b ? (a = b, 1) : 0; }

template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    for (int i = 0; i < (int) v.size(); ++i) os << v[i] << " ";
    return os;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(15);

    while (true) {
        int n;
        cin >> n;
        if (n == 0) break;
        vector<vector<int>> times(n, vector<int>(3));
        rep(i,0,n) {
            rep(j,0,3) cin >> times[i][j];
        }

        auto diff = [&](auto& t1, auto& t2) {
            int x1 = t1[0]/12*3600 + t1[1]*60 + t1[2];
            int x2 = t2[0]/12*3600 + t2[1]*60 + t2[2];
            int dt = x2 - x1;
            if (dt < 0) dt += 60*60*60;
            return dt;
        };

        auto rotate = [&](auto t, int d) {
            rep(j,0,3) t[j] = (t[j] + d) % 60;
            if (t[0]%5 != t[1]/12) return vector<int>();
            return t;
        };

        auto print = [&](auto& t1, auto& t2) {
            printf("%02d:%02d:%02d %02d:%02d:%02d\n", t1[0]/5, t1[1], t1[2], t2[0]/5, t2[1], t2[2]);
        };

        int dt = 1e9;
        vector<int> ans1(3), ans2(3);
        // fix the earliest time
        rep(i,0,n) {
            // fix the order of hands
            vector<int> ord = {0, 1, 2};
            do {
                vector<int> timei0(3);
                rep(j,0,3) timei0[j] = times[i][ord[j]];
                rep(d,0,60) {
                    auto timei1 = rotate(timei0, d);
                    if (timei1.empty()) continue;

                    vector<int> timei2 = timei1;

                    // get the time right after the timei1
                    rep(k,0,n) {
                        if (i == k) continue;
                        vector<int> after = {10000, 10000, 10000};

                        vector<int> ord2 = {0, 1, 2};
                        do {
                            vector<int> timek0(3);
                            rep(j,0,3) timek0[j] = times[k][ord2[j]];
                            rep(d2,0,60) {
                                vector<int> timek1 = rotate(timek0, d2);
                                if (!timek1.empty() && timei1 <= timek1) {
                                    chmin(after, timek1);
                                }
                            }
                        } while (next_permutation(all(ord2)));
                        chmax(timei2, after);
                    }
                    int ndt = diff(timei1, timei2);
                    if (ndt < dt || (ndt == dt && timei1 < ans1)) {
                        dt = ndt;
                        ans1 = timei1;
                        ans2 = timei2;
                    }
                }
            } while (next_permutation(all(ord)));
        }
        print(ans1, ans2);
    }
}
accuracy: 1
time_ms: 200
memory_kb: 3212
final_rank: 6

code_snippet: #include <cstdio>
#include <vector>
#include <set>
#include <functional>
using namespace std;

int getID(int x, int y, int z) {
  int py = y / 12;
  if (py != x % 5) return -1;
  return z + y * 60 + (x / 5) * 60 * 60; 
}

int main() {
  vector<vector<int>> pos;
  vector<int> vis(3, 0);
  vector<int> a(3);
        
  function<void(int)> dfs = [&](int p) {
    if (p == 3) {
      pos.push_back(a);
    } else {
      for (int i = 0; i < 3; i++) {
        if (!vis[i]) {
          vis[i] = 1;
          a[p] = i;
          dfs(p + 1);
          vis[i] = 0; 
        }
      }
    }
  };
  dfs(0);
      
  int n;
while (scanf("%d", &n) == 1) {
  if (n == 0) break;
  vector<set<int>> have(n);
  for (int it = 0; it < n; it++) {
    vector<int> b(3);
    for (int i = 0; i < 3; i++) scanf("%d", &b[i]);
    for (auto cur: pos) {
      int x = b[cur[0]];
      int y = b[cur[1]];
      int z=  b[cur[2]];
      for (int j = 0; j < 60; j++) {
        int x0 = (x + j) % 60;
        int y0 = (y + j) % 60;
        int z0 = (z + j) % 60;
        // int id = z0 + y0 * 60 + x0 * 60 * 12;
        int id = getID(x0, y0, z0);
        if (id != -1) have[it].insert(id);
      }
    }
  }
  int ans = -1;
  int u = -1, v = -1;
  int cycle = 12 * 60 * 60;
  for (int s = 0; s < cycle; s++) {
    int low = s;
    for (int i = 0; i < n; i++) {
      auto find = have[i].lower_bound(s);
      if (find != have[i].end()) {
        int take = *find;
        low = max(low, take); 
      } else {
        int take = cycle + *(have[i].begin());
        low = max(low, take);
      }
    }
    if (ans == -1 || low - s + 1 < ans) {
      ans = low - s + 1;
      u = s, v = low; 
    }
  }
  auto out = [&](int u) {
    u = u % cycle;
    vector<int> c;
    for (int i = 0; i < 3; i++) {
      c.push_back(u % 60);
      u /= 60; 
    }
    for (int i = (int)c.size() - 1; i >= 0; i--) {
      printf("%02d", c[i]);
      if (i) printf(":"); 
    }
  };
  /*
  for (int i = 0; i < n; i++) {
    printf("i = %d\n", i);
    for (int u: have[i]) { 
      out(u); 
      printf("\n");
    }
    printf("\n");
  }*/
  // printf("u = %d, v = %d: %d\n", u, v, ans);
  out(u);
  printf(" ");
  out(v);
  printf("\n");
}
  return 0; 
}
accuracy: 1
time_ms: 30
memory_kb: 2992
final_rank: 1

code_snippet: // #pragma comment(linker, "/stack:200000000")

#include <bits/stdc++.h>

#include <limits>
#include <type_traits>

namespace suisen {
// ! utility
template <typename ...Types>
using constraints_t = std::enable_if_t<std::conjunction_v<Types...>, std::nullptr_t>;
template <bool cond_v, typename Then, typename OrElse>
constexpr decltype(auto) constexpr_if(Then&& then, OrElse&& or_else) {
    if constexpr (cond_v) {
        return std::forward<Then>(then);
    } else {
        return std::forward<OrElse>(or_else);
    }
}

// ! function
template <typename ReturnType, typename Callable, typename ...Args>
using is_same_as_invoke_result = std::is_same<std::invoke_result_t<Callable, Args...>, ReturnType>;
template <typename F, typename T>
using is_uni_op = is_same_as_invoke_result<T, F, T>;
template <typename F, typename T>
using is_bin_op = is_same_as_invoke_result<T, F, T, T>;

template <typename Comparator, typename T>
using is_comparator = std::is_same<std::invoke_result_t<Comparator, T, T>, bool>;

// ! integral
template <typename T, typename = constraints_t<std::is_integral<T>>>
constexpr int bit_num = std::numeric_limits<std::make_unsigned_t<T>>::digits;
template <typename T, unsigned int n>
struct is_nbit { static constexpr bool value = bit_num<T> == n; };
template <typename T, unsigned int n>
static constexpr bool is_nbit_v = is_nbit<T, n>::value;

// ?
template <typename T>
struct safely_multipliable {};
template <>
struct safely_multipliable<int> { using type = long long; };
template <>
struct safely_multipliable<long long> { using type = __int128_t; };
template <>
struct safely_multipliable<float> { using type = float; };
template <>
struct safely_multipliable<double> { using type = double; };
template <>
struct safely_multipliable<long double> { using type = long double; };
template <typename T>
using safely_multipliable_t = typename safely_multipliable<T>::type;

} // namespace suisen

// ! type aliases
using i128 = __int128_t;
using u128 = __uint128_t;
using ll = long long;
using uint = unsigned int;
using ull  = unsigned long long;

template <typename T> using vec  = std::vector<T>;
template <typename T> using vec2 = vec<vec <T>>;
template <typename T> using vec3 = vec<vec2<T>>;
template <typename T> using vec4 = vec<vec3<T>>;

template <typename T>
using pq_greater = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template <typename T, typename U>
using umap = std::unordered_map<T, U>;

// ! macros (capital: internal macro)
#define OVERLOAD2(_1,_2,name,...) name
#define OVERLOAD3(_1,_2,_3,name,...) name
#define OVERLOAD4(_1,_2,_3,_4,name,...) name

#define REP4(i,l,r,s)  for(std::remove_reference_t<std::remove_const_t<decltype(r)>>i=(l);i<(r);i+=(s))
#define REP3(i,l,r)    REP4(i,l,r,1)
#define REP2(i,n)      REP3(i,0,n)
#define REPINF3(i,l,s) for(std::remove_reference_t<std::remove_const_t<decltype(l)>>i=(l);;i+=(s))
#define REPINF2(i,l)   REPINF3(i,l,1)
#define REPINF1(i)     REPINF2(i,0)
#define RREP4(i,l,r,s) for(std::remove_reference_t<std::remove_const_t<decltype(r)>>i=(l)+fld((r)-(l)-1,s)*(s);i>=(l);i-=(s))
#define RREP3(i,l,r)   RREP4(i,l,r,1)
#define RREP2(i,n)     RREP3(i,0,n)

#define rep(...)    OVERLOAD4(__VA_ARGS__, REP4   , REP3   , REP2   )(__VA_ARGS__)
#define rrep(...)   OVERLOAD4(__VA_ARGS__, RREP4  , RREP3  , RREP2  )(__VA_ARGS__)
#define repinf(...) OVERLOAD3(__VA_ARGS__, REPINF3, REPINF2, REPINF1)(__VA_ARGS__)

#define CAT_I(a, b) a##b
#define CAT(a, b) CAT_I(a, b)
#define UNIQVAR(tag) CAT(tag, __LINE__)
#define loop(n) for (std::remove_reference_t<std::remove_const_t<decltype(n)>> UNIQVAR(loop_variable) = n; UNIQVAR(loop_variable) --> 0;)

#define all(iterable) (iterable).begin(), (iterable).end()
#define input(type, ...) type __VA_ARGS__; read(__VA_ARGS__)

// ! I/O utilities

// pair
template <typename T, typename U>
std::ostream& operator<<(std::ostream& out, const std::pair<T, U> &a) {
    return out << a.first << ' ' << a.second;
}
// tuple
template <unsigned int N = 0, typename ...Args>
std::ostream& operator<<(std::ostream& out, const std::tuple<Args...> &a) {
    if constexpr (N >= std::tuple_size_v<std::tuple<Args...>>) {
        return out;
    } else {
        out << std::get<N>(a);
        if constexpr (N + 1 < std::tuple_size_v<std::tuple<Args...>>) {
            out << ' ';
        }
        return operator<<<N + 1>(out, a);
    }
}
// vector
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T> &a) {
    for (auto it = a.begin(); it != a.end();) {
        out << *it;
        if (++it != a.end()) out << ' ';
    }
    return out;
}
inline void print() { std::cout << '\n'; }
template <typename Head, typename... Tail>
inline void print(const Head &head, const Tail &...tails) {
    std::cout << head;
    if (sizeof...(tails)) std::cout << ' ';
    print(tails...);
}
template <typename Iterable>
auto print_all(const Iterable& v, std::string sep = " ", std::string end = "\n") -> decltype(std::cout << *v.begin(), void()) {
    for (auto it = v.begin(); it != v.end();) {
        std::cout << *it;
        if (++it != v.end()) std::cout << sep;
    }
    std::cout << end;
}

// pair
template <typename T, typename U>
std::istream& operator>>(std::istream& in, std::pair<T, U> &a) {
    return in >> a.first >> a.second;
}
// tuple
template <unsigned int N = 0, typename ...Args>
std::istream& operator>>(std::istream& in, std::tuple<Args...> &a) {
    if constexpr (N >= std::tuple_size_v<std::tuple<Args...>>) {
        return in;
    } else {
        return operator>><N + 1>(in >> std::get<N>(a), a);
    }
}
// vector
template <typename T>
std::istream& operator>>(std::istream& in, std::vector<T> &a) {
    for (auto it = a.begin(); it != a.end(); ++it) in >> *it;
    return in;
}
template <typename ...Args>
void read(Args &...args) {
    ( std::cin >> ... >> args );
}

// ! integral utilities

// Returns pow(-1, n)
template <typename T>
constexpr inline int pow_m1(T n) {
    return -(n & 1) | 1;
}
// Returns pow(-1, n)
template <>
constexpr inline int pow_m1<bool>(bool n) {
    return -int(n) | 1;
}

// Returns floor(x / y)
template <typename T>
constexpr inline T fld(const T x, const T y) {
    return (x ^ y) >= 0 ? x / y : (x - (y + pow_m1(y >= 0))) / y;
}
template <typename T>
constexpr inline T cld(const T x, const T y) {
    return (x ^ y) <= 0 ? x / y : (x + (y + pow_m1(y >= 0))) / y;
}

template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int popcount(const T x) { return __builtin_popcount(x); }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int popcount(const T x) { return __builtin_popcountll(x); }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int count_lz(const T x) { return x ? __builtin_clz(x)   : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int count_lz(const T x) { return x ? __builtin_clzll(x) : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int count_tz(const T x) { return x ? __builtin_ctz(x)   : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int count_tz(const T x) { return x ? __builtin_ctzll(x) : suisen::bit_num<T>; }
template <typename T>
constexpr inline int floor_log2(const T x) { return suisen::bit_num<T> - 1 - count_lz(x); }
template <typename T>
constexpr inline int ceil_log2(const T x)  { return floor_log2(x) + ((x & -x) != x); }
template <typename T>
constexpr inline int kth_bit(const T x, const unsigned int k) { return (x >> k) & 1; }
template <typename T>
constexpr inline int parity(const T x) { return popcount(x) & 1; }

struct all_subset {
    struct all_subset_iter {
        const int s; int t;
        constexpr all_subset_iter(int s) : s(s), t(s + 1) {}
        constexpr auto operator*() const { return t; }
        constexpr auto operator++() {}
        constexpr auto operator!=(std::nullptr_t) { return t ? (--t &= s, true) : false; }
    };
    int s;
    constexpr all_subset(int s) : s(s) {}
    constexpr auto begin() { return all_subset_iter(s); }
    constexpr auto end()   { return nullptr; }
};

// ! container

template <typename T, typename Comparator, suisen::constraints_t<suisen::is_comparator<Comparator, T>> = nullptr>
auto priqueue_comp(const Comparator comparator) {
    return std::priority_queue<T, std::vector<T>, Comparator>(comparator);
}

template <typename Iterable>
auto isize(const Iterable &iterable) -> decltype(int(iterable.size())) {
    return iterable.size();
}

template <typename T, typename Gen, suisen::constraints_t<suisen::is_same_as_invoke_result<T, Gen, int>> = nullptr>
auto generate_vector(int n, Gen generator) {
    std::vector<T> v(n);
    for (int i = 0; i < n; ++i) v[i] = generator(i);
    return v;
}

template <typename T>
void sort_unique_erase(std::vector<T> &a) {
    std::sort(a.begin(), a.end());
    a.erase(std::unique(a.begin(), a.end()), a.end());
}

// ! other utilities

// x <- min(x, y). returns true iff `x` has chenged.
template <typename T>
inline bool chmin(T &x, const T &y) {
    if (y >= x) return false;
    x = y;
    return true;
}
// x <- max(x, y). returns true iff `x` has chenged.
template <typename T>
inline bool chmax(T &x, const T &y) {
    if (y <= x) return false;
    x = y;
    return true;
}

namespace suisen {}
using namespace suisen;
using namespace std;

struct io_setup {
    io_setup(int precision = 20) {
        std::ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        std::cout << std::fixed << std::setprecision(precision);
    }
} io_setup_{};

// ! code from here

constexpr int H = 12;
constexpr int M = 60;
constexpr int S = 60;
constexpr int D = H * M * S;

constexpr int T = 60;

struct Time {
    int t;

    Time& operator++() {
        ++t;
        return *this;
    }
    operator int() { return t; }

    int hour()   const { return t / (M * S); }
    int minute() const { return t / S % M; }
    int second() const { return t % S; }

    int hour_hand()   const { return t / S / 12; }
    int minute_hand() const { return t / S % T; }
    int second_hand() const { return t % T; }

    friend ostream& operator<<(ostream& out, const Time& t) {
        return out << t.hour() << ':' << t.minute() << ':' << t.second();
    }
};

int main() {
    while (true) {
        input(int, n);
        if (n == 0) break;
        vector<array<int, 3>> watches(n);
        for (auto &[x, y, z] : watches) read(x, y, z);
        vector<int> t(D, 0);
        for (auto& hands : watches) {
            vector<int> cum_min(D, 2 * D);
            sort(all(hands));
            do {
                loop(T) {
                    int m = (hands[1] - 12 * hands[0]) % 60;
                    if (m < 0) m += 60;
                    if (m < 12) {
                        int x = hands[0] * 12 * S + m * S + hands[2];
                        chmin(cum_min[x], x);
                    }
                    ++hands[0] %= T, ++hands[1] %= T, ++hands[2] %= T;
                }
            } while (next_permutation(all(hands)));
            rrep(s, D) {
                if (s + 1 < D) chmin(cum_min[s], cum_min[s + 1]);
                chmax(t[s], cum_min[s]);
            }
        }
        int min_interval = D - 1, aminl = 0;
        rep(s, D) {
            if (chmin(min_interval, t[s] - s)) {
                aminl = s;
            }
        }
        Time fr { aminl }, to { aminl + min_interval };
        printf("%02d:%02d:%02d %02d:%02d:%02d\n", fr.hour(), fr.minute(), fr.second(), to.hour(), to.minute(), to.second());
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3352
final_rank: 8

code_snippet: // #pragma comment(linker, "/stack:200000000")

#include <bits/stdc++.h>

#include <limits>
#include <type_traits>

namespace suisen {
// ! utility
template <typename ...Types>
using constraints_t = std::enable_if_t<std::conjunction_v<Types...>, std::nullptr_t>;
template <bool cond_v, typename Then, typename OrElse>
constexpr decltype(auto) constexpr_if(Then&& then, OrElse&& or_else) {
    if constexpr (cond_v) {
        return std::forward<Then>(then);
    } else {
        return std::forward<OrElse>(or_else);
    }
}

// ! function
template <typename ReturnType, typename Callable, typename ...Args>
using is_same_as_invoke_result = std::is_same<std::invoke_result_t<Callable, Args...>, ReturnType>;
template <typename F, typename T>
using is_uni_op = is_same_as_invoke_result<T, F, T>;
template <typename F, typename T>
using is_bin_op = is_same_as_invoke_result<T, F, T, T>;

template <typename Comparator, typename T>
using is_comparator = std::is_same<std::invoke_result_t<Comparator, T, T>, bool>;

// ! integral
template <typename T, typename = constraints_t<std::is_integral<T>>>
constexpr int bit_num = std::numeric_limits<std::make_unsigned_t<T>>::digits;
template <typename T, unsigned int n>
struct is_nbit { static constexpr bool value = bit_num<T> == n; };
template <typename T, unsigned int n>
static constexpr bool is_nbit_v = is_nbit<T, n>::value;

// ?
template <typename T>
struct safely_multipliable {};
template <>
struct safely_multipliable<int> { using type = long long; };
template <>
struct safely_multipliable<long long> { using type = __int128_t; };
template <>
struct safely_multipliable<float> { using type = float; };
template <>
struct safely_multipliable<double> { using type = double; };
template <>
struct safely_multipliable<long double> { using type = long double; };
template <typename T>
using safely_multipliable_t = typename safely_multipliable<T>::type;

} // namespace suisen

// ! type aliases
using i128 = __int128_t;
using u128 = __uint128_t;
using ll = long long;
using uint = unsigned int;
using ull  = unsigned long long;

template <typename T> using vec  = std::vector<T>;
template <typename T> using vec2 = vec<vec <T>>;
template <typename T> using vec3 = vec<vec2<T>>;
template <typename T> using vec4 = vec<vec3<T>>;

template <typename T>
using pq_greater = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template <typename T, typename U>
using umap = std::unordered_map<T, U>;

// ! macros (capital: internal macro)
#define OVERLOAD2(_1,_2,name,...) name
#define OVERLOAD3(_1,_2,_3,name,...) name
#define OVERLOAD4(_1,_2,_3,_4,name,...) name

#define REP4(i,l,r,s)  for(std::remove_reference_t<std::remove_const_t<decltype(r)>>i=(l);i<(r);i+=(s))
#define REP3(i,l,r)    REP4(i,l,r,1)
#define REP2(i,n)      REP3(i,0,n)
#define REPINF3(i,l,s) for(std::remove_reference_t<std::remove_const_t<decltype(l)>>i=(l);;i+=(s))
#define REPINF2(i,l)   REPINF3(i,l,1)
#define REPINF1(i)     REPINF2(i,0)
#define RREP4(i,l,r,s) for(std::remove_reference_t<std::remove_const_t<decltype(r)>>i=(l)+fld((r)-(l)-1,s)*(s);i>=(l);i-=(s))
#define RREP3(i,l,r)   RREP4(i,l,r,1)
#define RREP2(i,n)     RREP3(i,0,n)

#define rep(...)    OVERLOAD4(__VA_ARGS__, REP4   , REP3   , REP2   )(__VA_ARGS__)
#define rrep(...)   OVERLOAD4(__VA_ARGS__, RREP4  , RREP3  , RREP2  )(__VA_ARGS__)
#define repinf(...) OVERLOAD3(__VA_ARGS__, REPINF3, REPINF2, REPINF1)(__VA_ARGS__)

#define CAT_I(a, b) a##b
#define CAT(a, b) CAT_I(a, b)
#define UNIQVAR(tag) CAT(tag, __LINE__)
#define loop(n) for (std::remove_reference_t<std::remove_const_t<decltype(n)>> UNIQVAR(loop_variable) = n; UNIQVAR(loop_variable) --> 0;)

#define all(iterable) (iterable).begin(), (iterable).end()
#define input(type, ...) type __VA_ARGS__; read(__VA_ARGS__)

// ! I/O utilities

// pair
template <typename T, typename U>
std::ostream& operator<<(std::ostream& out, const std::pair<T, U> &a) {
    return out << a.first << ' ' << a.second;
}
// tuple
template <unsigned int N = 0, typename ...Args>
std::ostream& operator<<(std::ostream& out, const std::tuple<Args...> &a) {
    if constexpr (N >= std::tuple_size_v<std::tuple<Args...>>) {
        return out;
    } else {
        out << std::get<N>(a);
        if constexpr (N + 1 < std::tuple_size_v<std::tuple<Args...>>) {
            out << ' ';
        }
        return operator<<<N + 1>(out, a);
    }
}
// vector
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T> &a) {
    for (auto it = a.begin(); it != a.end();) {
        out << *it;
        if (++it != a.end()) out << ' ';
    }
    return out;
}
inline void print() { std::cout << '\n'; }
template <typename Head, typename... Tail>
inline void print(const Head &head, const Tail &...tails) {
    std::cout << head;
    if (sizeof...(tails)) std::cout << ' ';
    print(tails...);
}
template <typename Iterable>
auto print_all(const Iterable& v, std::string sep = " ", std::string end = "\n") -> decltype(std::cout << *v.begin(), void()) {
    for (auto it = v.begin(); it != v.end();) {
        std::cout << *it;
        if (++it != v.end()) std::cout << sep;
    }
    std::cout << end;
}

// pair
template <typename T, typename U>
std::istream& operator>>(std::istream& in, std::pair<T, U> &a) {
    return in >> a.first >> a.second;
}
// tuple
template <unsigned int N = 0, typename ...Args>
std::istream& operator>>(std::istream& in, std::tuple<Args...> &a) {
    if constexpr (N >= std::tuple_size_v<std::tuple<Args...>>) {
        return in;
    } else {
        return operator>><N + 1>(in >> std::get<N>(a), a);
    }
}
// vector
template <typename T>
std::istream& operator>>(std::istream& in, std::vector<T> &a) {
    for (auto it = a.begin(); it != a.end(); ++it) in >> *it;
    return in;
}
template <typename ...Args>
void read(Args &...args) {
    ( std::cin >> ... >> args );
}

// ! integral utilities

// Returns pow(-1, n)
template <typename T>
constexpr inline int pow_m1(T n) {
    return -(n & 1) | 1;
}
// Returns pow(-1, n)
template <>
constexpr inline int pow_m1<bool>(bool n) {
    return -int(n) | 1;
}

// Returns floor(x / y)
template <typename T>
constexpr inline T fld(const T x, const T y) {
    return (x ^ y) >= 0 ? x / y : (x - (y + pow_m1(y >= 0))) / y;
}
template <typename T>
constexpr inline T cld(const T x, const T y) {
    return (x ^ y) <= 0 ? x / y : (x + (y + pow_m1(y >= 0))) / y;
}

template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int popcount(const T x) { return __builtin_popcount(x); }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int popcount(const T x) { return __builtin_popcountll(x); }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int count_lz(const T x) { return x ? __builtin_clz(x)   : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int count_lz(const T x) { return x ? __builtin_clzll(x) : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int count_tz(const T x) { return x ? __builtin_ctz(x)   : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int count_tz(const T x) { return x ? __builtin_ctzll(x) : suisen::bit_num<T>; }
template <typename T>
constexpr inline int floor_log2(const T x) { return suisen::bit_num<T> - 1 - count_lz(x); }
template <typename T>
constexpr inline int ceil_log2(const T x)  { return floor_log2(x) + ((x & -x) != x); }
template <typename T>
constexpr inline int kth_bit(const T x, const unsigned int k) { return (x >> k) & 1; }
template <typename T>
constexpr inline int parity(const T x) { return popcount(x) & 1; }

struct all_subset {
    struct all_subset_iter {
        const int s; int t;
        constexpr all_subset_iter(int s) : s(s), t(s + 1) {}
        constexpr auto operator*() const { return t; }
        constexpr auto operator++() {}
        constexpr auto operator!=(std::nullptr_t) { return t ? (--t &= s, true) : false; }
    };
    int s;
    constexpr all_subset(int s) : s(s) {}
    constexpr auto begin() { return all_subset_iter(s); }
    constexpr auto end()   { return nullptr; }
};

// ! container

template <typename T, typename Comparator, suisen::constraints_t<suisen::is_comparator<Comparator, T>> = nullptr>
auto priqueue_comp(const Comparator comparator) {
    return std::priority_queue<T, std::vector<T>, Comparator>(comparator);
}

template <typename Iterable>
auto isize(const Iterable &iterable) -> decltype(int(iterable.size())) {
    return iterable.size();
}

template <typename T, typename Gen, suisen::constraints_t<suisen::is_same_as_invoke_result<T, Gen, int>> = nullptr>
auto generate_vector(int n, Gen generator) {
    std::vector<T> v(n);
    for (int i = 0; i < n; ++i) v[i] = generator(i);
    return v;
}

template <typename T>
void sort_unique_erase(std::vector<T> &a) {
    std::sort(a.begin(), a.end());
    a.erase(std::unique(a.begin(), a.end()), a.end());
}

// ! other utilities

// x <- min(x, y). returns true iff `x` has chenged.
template <typename T>
inline bool chmin(T &x, const T &y) {
    if (y >= x) return false;
    x = y;
    return true;
}
// x <- max(x, y). returns true iff `x` has chenged.
template <typename T>
inline bool chmax(T &x, const T &y) {
    if (y <= x) return false;
    x = y;
    return true;
}

namespace suisen {}
using namespace suisen;
using namespace std;

struct io_setup {
    io_setup(int precision = 20) {
        std::ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        std::cout << std::fixed << std::setprecision(precision);
    }
} io_setup_{};

// ! code from here

constexpr int H = 12;
constexpr int M = 60;
constexpr int S = 60;
constexpr int D = H * M * S;

constexpr int T = 60;

struct Time {
    int t;

    Time& operator++() {
        ++t;
        return *this;
    }
    operator int() { return t; }

    int hour()   const { return t / (M * S); }
    int minute() const { return t / S % M; }
    int second() const { return t % S; }

    int hour_hand()   const { return t / S / 12; }
    int minute_hand() const { return t / S % T; }
    int second_hand() const { return t % T; }

    friend ostream& operator<<(ostream& out, const Time& t) {
        return out << t.hour() << ':' << t.minute() << ':' << t.second();
    }
};

int main() {
    while (true) {
        input(int, n);
        if (n == 0) break;
        vector<array<int, 3>> watches(n);
        for (auto &[x, y, z] : watches) read(x, y, z);
        int min_interval = D - 1;
        int aminl = 0;
        for (int s = 0; s < D; ++s) {
            int t = s;
            for (auto& hands : watches) {
                int mt = 2 * D;
                sort(all(hands));
                do {
                    loop(T) {
                        int m = (hands[1] - 12 * hands[0]) % 60;
                        if (m < 0) m += 60;
                        if (m < 12) {
                            int x = hands[0] * 12 * S + m * S + hands[2];
                            if (x >= s) chmin(mt, x);
                        }
                        ++hands[0] %= T, ++hands[1] %= T, ++hands[2] %= T;
                    }
                } while (next_permutation(all(hands)));
                chmax(t, mt);
                if (t >= s + min_interval) break;
            }
            if (chmin(min_interval, t - s)) {
                aminl = s;
            }
        }
        Time fr{ aminl }, to{ aminl + min_interval };
        printf("%02d:%02d:%02d %02d:%02d:%02d\n", fr.hour(), fr.minute(), fr.second(), to.hour(), to.minute(), to.second());
    }
    return 0;
}
accuracy: 1
time_ms: 4320
memory_kb: 3536
final_rank: 17

code_snippet: #include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define Inf 1000000001

void Put(int t){
	int s = t%60;
	t /= 60;
	int m = t%60;
	t /= 60;
	int h = t;
	
	printf("%02d:%02d:%02d",h,m,s);
}

int main(){
	
	vector<array<int,3>> A(12*60*60);
	
	rep(i,12*60*60){
		int ts = i%60;
		int tm = (i/60)%60;
		int th = (i/(60*12))%60;
		A[i] = {th,tm,ts};
	}
	
	
	
	while(true){
		int n;
		cin>>n;
		
		if(n==0)break;
		
		vector<array<int,3>> s(n);
		rep(i,n){
			rep(j,3){
				cin>>s[i][j];
			}
		}
		
		vector<vector<int>> times(n);
		
		rep(i,n){
			vector<int> tt = {0,1,2};
			do{
				rep(j,60){
					array<int,3> B = {s[i][tt[0]],s[i][tt[1]],s[i][tt[2]]};
					int d = distance(A.begin(),lower_bound(A.begin(),A.end(),B));
					if(d!=A.size() && A[d]==B){
						times[i].push_back(d);
					}
					rep(k,3){
						s[i][k] ++;
						s[i][k] %= 60;
					}
				}
			}
			while(next_permutation(tt.begin(),tt.end()));
			
			sort(times[i].begin(),times[i].end());
			times[i].erase(unique(times[i].begin(),times[i].end()),times[i].end());
		}
		
		vector<pair<int,int>> ans;
		rep(i,12*60*60){
			int M = i;
			rep(j,n){
				int d = distance(times[j].begin(),lower_bound(times[j].begin(),times[j].end(),i));
				if(d==times[j].size()){
					M = Inf;
				}
				else{
					M = max(M,times[j][d]);
				}				
			}
			if(M==Inf)continue;
			ans.emplace_back(i,M);
		}
		
		int ind = 0;
		
		rep(i,ans.size()){
			if(ans[i].second-ans[i].first < ans[ind].second-ans[ind].first)ind = i;
		}
		
		Put(ans[ind].first);
		cout<<' ';
		Put(ans[ind].second);
		cout<<endl;
		
	}
	
	return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 4304
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;
const int MAX = 60 * 60 * 12, INF = 1e9;

int time(int s, int t, int u, int x) {  // 時針、分針、秒針がs,t,uにあって基準がxのときの時間
    int res = 0;
    s = (s + 60 - x) % 60;
    t = (t + 60 - x) % 60;
    u = (u + 60 - x) % 60;
    if (s % 5 != t / 12) return INF;
    res += s / 5 * 3600;
    res += t % 60 * 60;
    res += u % 60 * 1;
    return res;
}

int cycle[8] = {10, 6, 0, 10, 6, 0, 10, 10};

string convert(int t) {
    string res = "";
    for (int i = 0; i < 8; i++) {
        if (i % 3 == 2)
            res += ':';
        else {
            res += char('0' + t % cycle[i]);
            t /= cycle[i];
        }
    }
    reverse(res.begin(), res.end());
    return res;
}

void solve(int n) {
    vector<vector<int>> cand(n);
    for (int i = 0; i < n; i++) {
        vector<int> v(3);
        for (int j = 0; j < 3; j++) cin >> v[j];
        for (int j = 0; j < 60; j++) {
            vector<int> ord(3);
            iota(ord.begin(), ord.end(), 0);
            do {
                cand[i].emplace_back(time(v[ord[0]], v[ord[1]], v[ord[2]], j));
            } while (next_permutation(ord.begin(), ord.end()));
        }
        cand[i].emplace_back(INF);
        sort(cand[i].begin(), cand[i].end());
    }

    int Min = MAX, L = 0, R = MAX;
    for (int l = 0; l < MAX; l++) {
        int r = l;
        for (int j = 0; j < n; j++) {
            int nxt = *lower_bound(cand[j].begin(), cand[j].end(), l);
            r = max(r, nxt);
        }
        if (r - l < Min) {
            Min = r - l;
            L = l, R = r;
        }
    }

    cout << convert(L) << ' ' << convert(R) << '\n';
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n;
    while (cin >> n, n) solve(n);
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 3412
final_rank: 10

code_snippet: #define LOCAL
#include <bits/stdc++.h>
using namespace std;
#pragma region Macros
typedef long long ll;
typedef __int128_t i128;
typedef unsigned int uint;
typedef unsigned long long ull;
#define ALL(x) (x).begin(), (x).end()

template <typename T> istream& operator>>(istream& is, vector<T>& v) {
    for (T& x : v) is >> x;
    return is;
}
template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) {
    for (int i = 0; i < (int)v.size(); i++) {
        os << v[i] << (i + 1 == (int)v.size() ? "" : " ");
    }
    return os;
}
template <typename T, typename U> ostream& operator<<(ostream& os, const pair<T, U>& p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template <typename T, typename U, typename V> ostream& operator<<(ostream& os, const tuple<T, U, V>& t) {
    os << '(' << get<0>(t) << ',' << get<1>(t) << ',' << get<2>(t) << ')';
    return os;
}
template <typename T, typename U, typename V, typename W> ostream& operator<<(ostream& os, const tuple<T, U, V, W>& t) {
    os << '(' << get<0>(t) << ',' << get<1>(t) << ',' << get<2>(t) << ',' << get<3>(t) << ')';
    return os;
}
template <typename T, typename U> ostream& operator<<(ostream& os, const map<T, U>& m) {
    os << '{';
    for (auto itr = m.begin(); itr != m.end();) {
        os << '(' << itr->first << ',' << itr->second << ')';
        if (++itr != m.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T, typename U> ostream& operator<<(ostream& os, const unordered_map<T, U>& m) {
    os << '{';
    for (auto itr = m.begin(); itr != m.end();) {
        os << '(' << itr->first << ',' << itr->second << ')';
        if (++itr != m.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const set<T>& s) {
    os << '{';
    for (auto itr = s.begin(); itr != s.end();) {
        os << *itr;
        if (++itr != s.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const multiset<T>& s) {
    os << '{';
    for (auto itr = s.begin(); itr != s.end();) {
        os << *itr;
        if (++itr != s.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const unordered_set<T>& s) {
    os << '{';
    for (auto itr = s.begin(); itr != s.end();) {
        os << *itr;
        if (++itr != s.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const deque<T>& v) {
    for (int i = 0; i < (int)v.size(); i++) {
        os << v[i] << (i + 1 == (int)v.size() ? "" : " ");
    }
    return os;
}

void debug_out() { cerr << '\n'; }
template <class Head, class... Tail> void debug_out(Head&& head, Tail&&... tail) {
    cerr << head;
    if (sizeof...(Tail) > 0) cerr << ", ";
    debug_out(move(tail)...);
}
#ifdef LOCAL
#define debug(...)                                                                   \
    cerr << " ";                                                                     \
    cerr << #__VA_ARGS__ << " :[" << __LINE__ << ":" << __FUNCTION__ << "]" << '\n'; \
    cerr << " ";                                                                     \
    debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif

template <typename T> T gcd(T x, T y) { return y != 0 ? gcd(y, x % y) : x; }
template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; }

template <class T1, class T2> inline bool chmin(T1& a, T2 b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template <class T1, class T2> inline bool chmax(T1& a, T2 b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
#pragma endregion

const int INF = 1e9;
const long long IINF = 1e18;
const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
const char dir[4] = {'D', 'R', 'U', 'L'};
const long long MOD = 1000000007;
// const long long MOD = 998244353;

const int MAX = 60 * 60 * 12;

int time(int s, int t, int u, int x) {  // 時針、分針、秒針がs,t,uにあって基準がxのときの時間
    int res = 0;
    s = (s + 60 - x) % 60;
    t = (t + 60 - x) % 60;
    u = (u + 60 - x) % 60;
    if (s % 5 != t / 12) return INF;
    res += s / 5 * 3600;
    res += t % 60 * 60;
    res += u % 60 * 1;
    return res;
}

int cycle[8] = {10, 6, 0, 10, 6, 0, 10, 10};

string convert(int t) {
    string res = "";
    for (int i = 0; i < 8; i++) {
        if (i % 3 == 2)
            res += ':';
        else {
            res += char('0' + t % cycle[i]);
            t /= cycle[i];
        }
    }
    reverse(res.begin(), res.end());
    return res;
}

void solve(int n) {
    vector<vector<int>> cand(n);
    for (int i = 0; i < n; i++) {
        vector<int> v(3);
        for (int j = 0; j < 3; j++) cin >> v[j];
        for (int j = 0; j < 60; j++) {
            vector<int> ord(3);
            iota(ord.begin(), ord.end(), 0);
            do {
                cand[i].emplace_back(time(v[ord[0]], v[ord[1]], v[ord[2]], j));
            } while (next_permutation(ord.begin(), ord.end()));
        }
        cand[i].emplace_back(INF);
        sort(cand[i].begin(), cand[i].end());
    }

    int Min = MAX, L = 0, R = MAX;
    for (int l = 0; l < MAX; l++) {
        int r = l;
        for (int j = 0; j < n; j++) {
            int nxt = *lower_bound(cand[j].begin(), cand[j].end(), l);
            r = max(r, nxt);
        }
        if (r - l < Min) {
            Min = r - l;
            L = l, R = r;
        }
    }

    cout << convert(L) << ' ' << convert(R) << '\n';
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n;
    while (cin >> n, n) solve(n);
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 3180
final_rank: 5

code_snippet: #include <bits/stdc++.h>

#define For(i, a, b) for (int i = (int)(a); i < (int)(b); ++i)
#define rFor(i, a, b) for (int i = (int)(a)-1; i >= (int)(b); --i)
#define rep(i, n) For((i), 0, (n))
#define rrep(i, n) rFor((i), (n), 0)
#define fi first
#define se second

using namespace std;

typedef long long lint;
typedef unsigned long long ulint;
typedef pair<int, int> pii;
typedef pair<lint, lint> pll;

template <class T>
bool chmax(T &a, const T &b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template <class T>
bool chmin(T &a, const T &b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}

template <class T>
T div_floor(T a, T b) {
    if (b < 0) a *= -1, b *= -1;
    return a >= 0 ? a / b : (a + 1) / b - 1;
}
template <class T>
T div_ceil(T a, T b) {
    if (b < 0) a *= -1, b *= -1;
    return a > 0 ? (a - 1) / b + 1 : a / b;
}

template <typename T>
struct coord_comp {
    vector<T> v;
    bool sorted = false;

    coord_comp() {}

    int size() { return v.size(); }

    void add(T x) { v.push_back(x); }

    void build() {
        sort(v.begin(), v.end());
        v.erase(unique(v.begin(), v.end()), v.end());
        sorted = true;
    }

    int get_idx(T x) {
        assert(sorted);
        return lower_bound(v.begin(), v.end(), x) - v.begin();
    }

    T &operator[](int i) { return v[i]; }
};

constexpr lint mod = 1000000007;
constexpr lint INF = mod * mod;
constexpr int MAX = 200010;

bool check(int h, int m) {
    int x = h % 5;
    return 12 * x <= m && m < 12 * (x + 1);
}

int main() {
    int n;
    while (scanf("%d", &n) && n) {
        int a[n][3];
        rep(i, n) rep(j, 3) scanf("%d", &a[i][j]);
        pair<int, pii> ans = {mod, {mod, mod}};
        rep(t, n) {
            int idx[3] = {0, 1, 2};
            do {
                rep(offset, 60) {
                    int h = (a[t][idx[0]] + offset) % 60,
                        m = (a[t][idx[1]] + offset) % 60,
                        s = (a[t][idx[2]] + offset) % 60;
                    if (!check(h, m)) continue;
                    int start = h / 5 * 3600 + m * 60 + s;
                    int end = 0;
                    rep(i, n) if (i != t) {
                        int idx2[3] = {0, 1, 2};
                        int min_time = mod;
                        do {
                            rep(offset2, 60) {
                                int h2 = (a[i][idx2[0]] + offset2) % 60,
                                    m2 = (a[i][idx2[1]] + offset2) % 60,
                                    s2 = (a[i][idx2[2]] + offset2) % 60;
                                if (!check(h2, m2)) continue;
                                int tmp = h2 / 5 * 3600 + m2 * 60 + s2;
                                if (tmp >= start) chmin(min_time, tmp);
                            }
                        } while (next_permutation(idx2, idx2 + 3));
                        chmax(end, min_time);
                    }
                    chmin(ans, {end - start, {start, end}});
                }
            } while (next_permutation(idx, idx + 3));
        }
        printf("%02d:%02d:%02d ", ans.se.fi / 3600, ans.se.fi % 3600 / 60,
               ans.se.fi % 60);
        printf("%02d:%02d:%02d\n", ans.se.se / 3600, ans.se.se % 3600 / 60,
               ans.se.se % 60);
    }
}
accuracy: 1
time_ms: 30
memory_kb: 3396
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;

const int N=10;

int n,s[N],t[N],u[N],last[N];

int hh(int x) { return x/12/60; }  // every 12 min !!!
int mm(int x) { return x/60%60; }
int ss(int x) { return x%60; }

string nn(int x) { string s; return s+char('0'+x/10%10)+char('0'+x%10); }

int match(int s1, int t1, int u1, int s2, int t2, int u2) {
    int ds=(s1-s2+60)%60;
    int dt=(t1-t2+60)%60;
    int du=(u1-u2+60)%60;
    return ds==dt && dt==du;
}

int solve() {
    cin>>n;
    if (n==0) return 0;

    for (int i=0; i<n; i++) cin>>s[i]>>t[i]>>u[i];

    int begin,end=-1;
    memset(last,-1,sizeof(last));
    for (int i=0; i<12*60*60; i++) {
        int a=hh(i), b=mm(i), c=ss(i);

        int j=i;
        for (int k=0; k<n; k++) {
            if (match(s[k],t[k],u[k],a,b,c) ||
                    match(s[k],t[k],u[k],a,c,b) ||
                    match(s[k],t[k],u[k],b,a,c) ||
                    match(s[k],t[k],u[k],b,c,a) ||
                    match(s[k],t[k],u[k],c,a,b) ||
                    match(s[k],t[k],u[k],c,b,a)) {
                last[k]=i;
            }
            if (last[k]<j) j=last[k];
        }

        if (j>=0 && (end==-1 || end-begin>i-j)) {
            end=i; begin=j;
        }
    }

    cout<<nn(hh(begin)/5)<<':'<<nn(mm(begin))<<':'<<nn(ss(begin))<<' '
            <<nn(hh(end)/5)<<':'<<nn(mm(end))<<':'<<nn(ss(end))<<'\n';
    return 1;
}

int main() {
    while (solve());
    return 0;
}
accuracy: 1
time_ms: 80
memory_kb: 3132
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long;
using PII = pair<ll, ll>;

#define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define ALL(x) x.begin(), x.end()
template <typename T> void chmin(T &a, const T &b) { a = min(a, b); }
template <typename T> void chmax(T &a, const T &b) { a = max(a, b); }

const ll INF = 1LL << 60;

struct FastIO {
    FastIO() {
        cin.tie(0);
        ios::sync_with_stdio(0);
    }
} fastiofastio;

const int DAY = 60 * 60 * 12;

bool exist[DAY][10];

string convert(int x) {
    int h = x / 3600;
    int m = (x % 3600) / 60;
    int s = x % 60;
    string ret = "";
    if (h < 10) {
        ret.push_back('0');
        ret.push_back(h + '0');
    } else {
        ret += to_string(h);
    }
    ret += ":";
    if (m < 10) {
        ret.push_back('0');
        ret.push_back(m + '0');
    } else {
        ret += to_string(m);
    }
    ret += ":";
    if (s < 10) {
        ret.push_back('0');
        ret.push_back(s + '0');
    } else {
        ret += to_string(s);
    }
    return ret;
}

int main() {
    while (1) {
        int n;
        cin >> n;
        if (n == 0)
            break;
        memset(exist, 0, sizeof(exist));
        for (int i = 0; i < n; i++) {
            int s, t, u;
            cin >> s >> t >> u;
            for (int j = 0; j < 60; j++) {
                int a[3] = {j, (j - s + t + 60) % 60, (j - s + u + 60) % 60};
                int perm[3] = {0, 1, 2};
                do {
                    if (a[perm[0]] % 5 == a[perm[1]] / 12) {
                        int x = a[perm[2]];
                        x += (a[perm[1]] % 12) * 60;
                        x += a[perm[0]] * 12 * 60;
                        exist[x][i] = 1;
                    }
                } while (next_permutation(perm, perm + 3));
            }
        }
        int l = 0, r = 0;
        int num[10] = {};
        int cnt = 0;
        int B = -1, E = -1;
        while (l < DAY) {
            while (r < DAY && cnt < n) {
                for (int i = 0; i < n; i++) {
                    if (exist[r][i]) {
                        if (num[i] == 0)
                            cnt++;
                        num[i]++;
                    }
                }
                r++;
            }
            if (cnt < n)
                break;
            //[l, r)
            if (B == -1 || E - B > r - l) {
                B = l;
                E = r;
            }
            for (int i = 0; i < n; i++) {
                if (exist[l][i]) {
                    num[i]--;
                    if (num[i] == 0)
                        cnt--;
                }
            }
            l++;
        }
        cout << convert(B) << " " << convert(E - 1) << endl;
    }
}
accuracy: 1
time_ms: 20
memory_kb: 3912
final_rank: 14

code_snippet: #include <bits/stdc++.h>
using namespace std;
int INF = 1000000;
string conv(int x){
  vector<int> t = {x / 3600, x % 3600 / 60, x % 60};
  string ans;
  for (int i = 0; i < 3; i++){
    string tmp = to_string(t[i]);
    if (tmp.size() == 1){
      tmp = '0' + tmp;
    }
    ans += tmp;
    if (i < 2){
      ans += ':';
    }
  }
  return ans;
}
int main(){
  while (1){
    int n;
    cin >> n;
    if (n == 0){
      break;
    }
    vector<vector<int>> t(n, vector<int>(3));
    for (int i = 0; i < n; i++){
      for (int j = 0; j < 3; j++){
        cin >> t[i][j];
      }
    }
    vector<vector<int>> s(60, vector<int>(60, 0));
    for (int i = 0; i < 60; i++){
      for (int j = 0; j < 60; j++){
        for (int k = 0; k < 60; k++){
          vector<int> p = {k, (i + k) % 60, (j + k) % 60};
          sort(p.begin(), p.end());
          while (1){
            for (int l = 0; l < n; l++){
              if (t[l] == p){
                s[i][j] |= 1 << l;
              }
            }
            if (!next_permutation(p.begin(), p.end())){
              break;
            }
          }
        }
      }
    }
    vector<int> s2(86400, 0);
    vector<int> p(3, 0);
    for (int i = 0; i < 86400; i++){
      if (i > 0){
        p[0] = (p[0] + 1) % 60;
        if (i % 60 == 0){
          p[1] = (p[1] + 1) % 60;
        }
        if (i % 720 == 0){
          p[2] = (p[2] + 1) % 60;
        }
      }
      int a = (p[1] - p[0] + 60) % 60;
      int b = (p[2] - p[0] + 60) % 60;
      s2[i] = s[a][b];
    }
    int mn = INF;
    int ansL, ansR;
    int R = 0;
    vector<int> cnt(n, 0);
    set<int> st;
    for (int L = 0; L < 86400; L++){
      while (R < 86400 && st.size() < n){
        for (int i = 0; i < n; i++){
          if (s2[R] >> i & 1){
            cnt[i]++;
            st.insert(i);
          }
        }
        R++;
        if (st.size() == n){
          break;
        }
      }
      if (st.size() == n){
        if (mn > R - L){
          mn = R - L;
          ansL = L;
          ansR = R - 1;
        }
      }
      for (int i = 0; i < n; i++){
        if (s2[L] >> i & 1){
          cnt[i]--;
          assert(cnt[i] >= 0);
          if (cnt[i] == 0){
            st.erase(i);
          }
        }
      }
    }
    cout << conv(ansL) << ' ' << conv(ansR) << endl;
  }
}
accuracy: 1
time_ms: 1860
memory_kb: 3656
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define mp make_pair
#define si(x) int(x.size())
const int mod=1000000007,MAX=200005,INF=1<<30;

string S(int t){
    string res;
    int a=t/3600;
    if(a<10) res+='0';
    res+=to_string(a);
    res+=':';
    
    t%=3600;
    int b=t/60;
    if(b<10) res+='0';
    res+=to_string(b);
    res+=':';
    
    int c=t%60;
    if(c<10) res+='0';
    res+=to_string(c);
    
    return res;
}

int main(){
    
    std::ifstream in("text.txt");
    std::cin.rdbuf(in.rdbuf());
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    while(1){
        int N;cin>>N;
        if(N==0) break;
        vector<vector<int>> A(N);
        for(int i=0;i<N;i++){
            vector<int> t(3);
            for(int j=0;j<3;j++) cin>>t[j];
            sort(all(t));
            
            do{
                for(int j=0;j<60;j++){
                    int a=(t[0]+j)%60,b=(t[1]+j)%60,c=(t[2]+j)%60;
                    
                    if(a%5!=b/12) continue;
                    
                    A[i].push_back((a/5)*3600+b*60+c);
                }
                
            }while(next_permutation(all(t)));
            
            sort(all(A[i]));
            A[i].erase(unique(all(A[i])),A[i].end());
        }
        
        pair<int,int> res={INF,INF};
        
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                if(i==j) continue;
                
                for(int a:A[i]){
                    for(int b:A[j]){
                        if(a>b) continue;
                        
                        bool ok=true;
                        for(int k=0;k<N;k++){
                            if(k==i||k==j) continue;
                            auto x=lower_bound(all(A[k]),a);
                            if(x==A[k].end()||*x>b) ok=false;
                        }
                        if(ok){
                            chmin(res,mp(b-a,a));
                        }
                    }
                }
            }
        }
        
        cout<<S(res.se)<<" "<<S(res.fi+res.se)<<endl;
    }
}
accuracy: 1
time_ms: 40
memory_kb: 3284
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
template<class T>
inline bool chmax(T &a, T b) {
    if(a < b) {
        a = b;
        return true;
    }
    return false;
}

template<class T>
inline bool chmin(T &a, T b) {
    if(a > b) {
        a = b;
        return true;
    }
    return false;
}

const long double EPS = 1e-10;
const long long INF = 1e18;
const long double PI = acos(-1.0L);
int N;
bool can[10][24*60*60];
int MAX = 24*60*60;
int factor[3] = {3600, 60, 1};
int num[10];

string f(ll x) {
    string ret;
    ll tmp = x / 3600;
    string T = to_string(tmp);
    if(T.size() == 1) T = "0" + T;
    ret = ret + T + ":";
    tmp = x / 60;
    tmp %= 60;
    T = to_string(tmp);
    if(T.size() == 1) T = "0" + T;
    ret = ret + T + ":";
    tmp = x;
    tmp %= 60;
    T = to_string(tmp);
    if(T.size() == 1) T = "0" + T;
    ret = ret + T;
    return ret;
}

void solve() {
    for(int i = 0; i < 10; i++) {
        assert(num[i] == 0);
        for(int j = 0; j < MAX; j++) {
            can[i][j] = false;
        }
    }
    for(int i = 0; i < N; i++) {
        vector<int> v(3);
        for(int j = 0; j < 3; j++) cin >> v[j];
        sort(v.begin(), v.end());
        do {
            for(int k = 0; k < 60; k++) {
                vector<int> w(3);
                for(int j = 0; j < 3; j++) {
                    w[j] = (v[j] + k) % 60;
                }
                for(int t = 0; t < MAX; t++) {
                    int a = t / 720;
                    a %= 60;
                    if(a != w[0]) continue;
                    a = t / 60;
                    a %= 60;
                    if(a != w[1]) continue;
                    a = t;
                    a %= 60;
                    if(a != w[2]) continue;
                    can[i][t] = true;
                }
            }
        } while(next_permutation(v.begin(), v.end()));
    }
    int ansl = 0;
    int ansr = MAX - 1;
    int ansinterval = MAX;
    int r = -1;
    for(int l = 0; l < MAX; l++) {
        while(true) {
            if(r == MAX) break;
            bool ok = true;
            for(int j = 0; j < N; j++) {
                if(num[j] == 0) ok = false;
            }
            if(ok) break;
            r++;
            if(r == MAX) break;
            for(int j = 0; j < N; j++) {
                if(can[j][r]) num[j]++;
            }
        }
        for(int j = 0; j < N; j++) {
            if(can[j][l]) num[j]--;
        }
        if(r == MAX) continue;
        int interval = r - l;
        if(chmin(ansinterval, interval)) {
            ansl = l;
            ansr = r;
        }
        //cerr << l << " " << r << endl;
    }
    cout << f(ansl) << " " << f(ansr) << endl;
}

int main() {
    //cout.precision(10);
    cin.tie(0);
    ios::sync_with_stdio(false);
    while(cin >> N) {
        if(N == 0) break;
        solve();
    }
    return 0;
}
accuracy: 1
time_ms: 8000
memory_kb: 4152
final_rank: 20

code_snippet: #define  _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES

#pragma comment (linker, "/STACK:526000000")

#include "bits/stdc++.h"

using namespace std;
typedef string::const_iterator State;
#define eps 1e-5L
#define MAX_MOD 1000000007LL
#define GYAKU 500000004LL
#define MOD 998244353LL
#define pb push_back
#define mp make_pair
typedef long long ll;
#define REP(a,b) for(long long (a) = 0;(a) < (b);++(a))
#define ALL(x) (x).begin(),(x).end()

// geometry library

typedef complex<long double> Point;
typedef pair<complex<long double>, complex<long double>> Line;

typedef struct Circle {
    complex<long double> center;
    long double r;
}Circle;

long double dot(Point a, Point b) {
    return (a.real() * b.real() + a.imag() * b.imag());
}
long double cross(Point a, Point b) {
    return (a.real() * b.imag() - a.imag() * b.real());
}

long double Dist_Line_Point(Line a, Point b) {
    if (dot(a.second - a.first, b - a.first) < eps) return abs(b - a.first);
    if (dot(a.first - a.second, b - a.second) < eps) return abs(b - a.second);
    return abs(cross(a.second - a.first, b - a.first)) / abs(a.second - a.first);
}

int is_intersected_ls(Line a, Line b) {
    return (cross(a.second - a.first, b.first - a.first) * cross(a.second - a.first, b.second - a.first) < eps) &&
        (cross(b.second - b.first, a.first - b.first) * cross(b.second - b.first, a.second - b.first) < eps);
}

Point intersection_l(Line a, Line b) {
    Point da = a.second - a.first;
    Point db = b.second - b.first;
    return a.first + da * cross(db, b.first - a.first) / cross(db, da);
}

long double Dist_Line_Line(Line a, Line b) {
    if (is_intersected_ls(a, b) == 1) {
        return 0;
    }
    return min({ Dist_Line_Point(a,b.first), Dist_Line_Point(a,b.second),Dist_Line_Point(b,a.first),Dist_Line_Point(b,a.second) });
}

pair<Point, Point> intersection_Circle_Circle(Circle a, Circle b) {
    long double dist = abs(a.center - b.center);
    assert(dist <= eps + a.r + b.r);
    assert(dist + eps >= abs(a.r - b.r));
    Point target = b.center - a.center;
    long double pointer = target.real() * target.real() + target.imag() * target.imag();
    long double aa = pointer + a.r * a.r - b.r * b.r;
    aa /= 2.0L;
    Point l{ (aa * target.real() + target.imag() * sqrt(pointer * a.r * a.r - aa * aa)) / pointer,
            (aa * target.imag() - target.real() * sqrt(pointer * a.r * a.r - aa * aa)) / pointer };
    Point r{ (aa * target.real() - target.imag() * sqrt(pointer * a.r * a.r - aa * aa)) / pointer,
        (aa * target.imag() + target.real() * sqrt(pointer * a.r * a.r - aa * aa)) / pointer };
    r = r + a.center;
    l = l + a.center;
    return mp(l, r);
}

//end of geometry

template<typename A>
A pows(A val, ll b) {
    assert(b >= 1);
    A ans = val;
    b--;
    while (b) {
        if (b % 2) {
            ans *= val;
        }
        val *= val;
        b /= 2LL;
    }
    return ans;
}

template<typename A>
class Compressor {
public:
    bool is_zipped = false;
    map<A, ll> zipper;
    map<ll, A> unzipper;
    queue<A> fetcher;
    Compressor() {
        is_zipped = false;
        zipper.clear();
        unzipper.clear();
    }
    void add(A now) {
        assert(is_zipped == false);
        zipper[now] = 1;
        fetcher.push(now);
    }
    void exec() {
        assert(is_zipped == false);
        int cnt = 0;
        for (auto i = zipper.begin(); i != zipper.end(); ++i) {
            i->second = cnt;
            unzipper[cnt] = i->first;
            cnt++;
        }
        is_zipped = true;
    }
    ll fetch() {
        assert(is_zipped == true);
        A hoge = fetcher.front();
        fetcher.pop();
        return zipper[hoge];
    }
    ll zip(A now) {
        assert(is_zipped == true);
        assert(zipper.find(now) != zipper.end());
        return zipper[now];
    }
    A unzip(ll a) {
        assert(is_zipped == true);
        assert(a < unzipper.size());
        return unzipper[a];
    }
    ll next(A now) {
        auto x = zipper.upper_bound(now);
        if (x == zipper.end()) return zipper.size();
        return (ll)((*x).second);
    }
    ll back(A now) {
        auto x = zipper.lower_bound(now);
        if (x == zipper.begin()) return -1;
        x--;
        return (ll)((*x).second);
    }
};

template<typename A>
class Matrix {
public:
    vector<vector<A>> data;
    Matrix(vector<vector<A>> a) :data(a) {

    }
    Matrix operator + (const Matrix obj) {
        vector<vector<A>> ans;
        assert(obj.data.size() == this->data.size());
        assert(obj.data[0].size() == this->data[0].size());
        REP(i, obj.data.size()) {
            ans.push_back(vector<A>());
            REP(q, obj.data[i].size()) {
                A hoge = obj.data[i][q] + (this->data[i][q]);
                ans.back().push_back(hoge);
            }
        }
        return Matrix(ans);
    }
    Matrix operator - (const Matrix obj) {
        vector<vector<A>> ans;
        assert(obj.data.size() == this->data.size());
        assert(obj.data[0].size() == this->data[0].size());
        REP(i, obj.data.size()) {
            ans.push_back(vector<A>());
            REP(q, obj.data[i].size()) {
                A hoge = this->data[i][q] - obj.data[i][q];
                ans.back().push_back(hoge);
            }
        }
        return Matrix(ans);
    }
    Matrix operator * (const Matrix obj) {
        vector<vector<A>> ans;
        assert(obj.data.size() == this->data[0].size());
        REP(i, this -> data.size()) {
            ans.push_back(vector<A>());
            REP(q, obj.data[0].size()) {
                A hoge = (this->data[i][0]) * (obj.data[0][q]);
                for (int t = 1; t < obj.data[i].size(); ++t) {
                    hoge += this->data[i][t] * obj.data[t][q];
                }
                ans.back().push_back(hoge);
            }
        }
        return Matrix(ans);
    }
    Matrix& operator *= (const Matrix obj) {
        *this = (*this * obj);
        return *this;
    }
    Matrix& operator += (const Matrix obj) {
        *this = (*this + obj);
        return *this;
    }
    Matrix& operator -= (const Matrix obj) {
        *this = (*this - obj);
        return *this;
    }
};

class modint {
public:
    using u64 = std::uint_fast64_t;
    u64 value = 0;
    u64 mod;
    modint(ll a, ll b) : value(((a% b) + 2 * b) % b), mod(b) {

    }
    modint operator+(const modint rhs) const {
        return modint(*this) += rhs;
    }
    modint operator-(const modint rhs) const {
        return modint(*this) -= rhs;
    }
    modint operator*(const modint rhs) const {
        return modint(*this) *= rhs;
    }
    modint operator/(const modint rhs) const {
        return modint(*this) /= rhs;
    }
    modint& operator+=(const modint rhs) {
        assert(rhs.mod == mod);
        value += rhs.value;
        if (value >= mod) {
            value -= mod;
        }
        return *this;
    }
    modint& operator-=(const modint rhs) {
        assert(rhs.mod == mod);
        if (value < rhs.value) {
            value += mod;
        }
        value -= rhs.value;
        return *this;
    }
    modint& operator*=(const modint rhs) {
        assert(rhs.mod == mod);
        value = (value * rhs.value) % mod;
        return *this;
    }
    modint& operator/=(modint rhs) {
        assert(rhs.mod == mod);
        ll rem = mod - 2;
        while (rem) {
            if (rem % 2) {
                *this *= rhs;
            }
            rhs *= rhs;
            rem /= 2LL;
        }
        return *this;
    }
    bool operator <(modint rhs) const {
        return value < rhs.value;
    }
    friend ostream& operator<<(ostream& os, modint& p) {
        os << p.value;
        return (os);
    }
};

class Dice {
public:
    vector<ll> vertexs;
    //Up: 0,Left: 1,Center: 2,Right: 3,Adj: 4, Down: 5
    Dice(vector<ll> init) :vertexs(init) {

    }
    //Look from Center
    void RtoL() {
        for (int q = 1; q < 4; ++q) {
            swap(vertexs[q], vertexs[q + 1]);
        }
    }
    void LtoR() {
        for (int q = 3; q >= 1; --q) {
            swap(vertexs[q], vertexs[q + 1]);
        }
    }
    void UtoD() {
        swap(vertexs[5], vertexs[4]);
        swap(vertexs[2], vertexs[5]);
        swap(vertexs[0], vertexs[2]);
    }
    void DtoU() {
        swap(vertexs[0], vertexs[2]);
        swap(vertexs[2], vertexs[5]);
        swap(vertexs[5], vertexs[4]);
    }
    bool ReachAble(Dice now) {
        set<Dice> hoge;
        queue<Dice> next;
        next.push(now);
        hoge.insert(now);
        while (next.empty() == false) {
            Dice seeing = next.front();
            next.pop();
            if (seeing == *this) return true;
            seeing.RtoL();
            if (hoge.count(seeing) == 0) {
                hoge.insert(seeing);
                next.push(seeing);
            }
            seeing.LtoR();
            seeing.LtoR();
            if (hoge.count(seeing) == 0) {
                hoge.insert(seeing);
                next.push(seeing);
            }
            seeing.RtoL();
            seeing.UtoD();
            if (hoge.count(seeing) == 0) {
                hoge.insert(seeing);
                next.push(seeing);
            }
            seeing.DtoU();
            seeing.DtoU();
            if (hoge.count(seeing) == 0) {
                hoge.insert(seeing);
                next.push(seeing);
            }
        }
        return false;
    }
    bool operator ==(const Dice& a) {
        for (int q = 0; q < 6; ++q) {
            if (a.vertexs[q] != (*this).vertexs[q]) {
                return false;
            }
        }
        return true;
    }
    bool operator <(const Dice& a) const {
        return (*this).vertexs < a.vertexs;
    }
};

pair<Dice, Dice> TwoDimDice(int center, int up) {
    int target = 1;
    while (true) {
        if (center != target && 7 - center != target && up != target && 7 - up != target) {
            break;
        }
        target++;
    }
    return mp(Dice(vector<ll>{up, target, center, 7 - target, 7 - center, 7 - up}), Dice(vector<ll>{up, 7 - target, center, target, 7 - center, 7 - up}));
}

tuple<Dice, Dice, Dice, Dice> OneDimDice(int center) {
    int bo = min(center, 7 - center);
    pair<int, int> goa;
    if (bo == 1) {
        goa = mp(2, 3);
    }
    else if (bo == 2) {
        goa = mp(1, 3);
    }
    else if (bo == 3) {
        goa = mp(1, 2);
    }
    tuple<Dice, Dice, Dice, Dice> now = make_tuple(Dice(vector<ll>{goa.first, goa.second, center, 7 - goa.second, 7 - center, 7 - goa.first}),
        Dice(vector<ll>{goa.first, 7 - goa.second, center, goa.second, 7 - center, 7 - goa.first}),
        Dice(vector<ll>{7 - goa.first, goa.second, center, 7 - goa.second, 7 - center, goa.first}),
        Dice(vector<ll>{7 - goa.first, 7 - goa.second, center, goa.second, 7 - center, goa.first}));
    return now;
}

template<typename A, typename B>
class Dijkstra {
public:
    vector<vector<pair<int, A>>> vertexs;
    B Cost_Function;
    Dijkstra(int n, B cost) : Cost_Function(cost) {
        vertexs = vector<vector<pair<int, A>>>(n, vector<pair<int, A>>{});
    }
    ~Dijkstra() {
        vertexs.clear();
    }
    void add_edge(int a, int b, A c) {
        vertexs[a].push_back(mp(b, c));
    }
    vector<ll> build_result(int StartPoint) {
        vector<ll> dist(vertexs.size(), 2e18);
        dist[StartPoint] = 0;
        priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> next;
        next.push(make_pair(0, StartPoint));
        while (next.empty() == false) {
            pair<ll, int> now = next.top();
            next.pop();
            if (dist[now.second] != now.first) continue;
            for (auto x : vertexs[now.second]) {
                ll now_cost = now.first + Cost_Function(x.second);
                if (dist[x.first] > now_cost) {
                    dist[x.first] = now_cost;
                    next.push(mp(now_cost, x.first));
                }
            }
        }
        return dist;
    }
};

class Dinic {
public:
    struct edge {
        int to;
        int cap;
        int rev;
    };
    vector<vector<edge>> Graph;
    vector<int> level;
    vector<int> itr;
    Dinic(int n) {
        Graph = vector<vector<edge>>(n, vector<edge>());
    }
    void add_edge(int a, int b, int cap) {
        Graph[a].push_back(edge{ b, cap ,(int)Graph[b].size() });
        Graph[b].push_back(edge{ a,0,(int)Graph[a].size() - 1 });
    }
    void bfs(int s) {
        level = vector<int>(Graph.size(), -1);
        level[s] = 0;
        queue<int> next;
        next.push(s);
        while (next.empty() == false) {
            int now = next.front();
            next.pop();
            for (auto x : Graph[now]) {
                if (x.cap == 0) continue;
                if (level[x.to] == -1) {
                    level[x.to] = level[now] + 1;
                    next.push(x.to);
                }
            }
        }
    }
    int dfs(int now, int goal, int val) {
        if (goal == now) return val;
        for (int& i = itr[now]; i < (int)Graph[now].size(); ++i) {
            edge& target = Graph[now][i];
            if (target.cap > 0 && level[now] < level[target.to]) {
                int d = dfs(target.to, goal, min(val, target.cap));
                if (d > 0) {
                    target.cap -= d;
                    Graph[target.to][target.rev].cap += d;
                    return d;
                }
            }
        }
        return 0;
    }
    int run(int s, int t) {
        int ans = 0;
        int f = 0;
        while (bfs(s), level[t] >= 0) {
            itr = vector<int>(Graph.size(), 0);
            while ((f = dfs(s, t, 1e9)) > 0) {
                ans += f;
            }
        }
        return ans;
    }
};

//by ei1333
//https://ei1333.github.io/luzhiled/snippets/structure/segment-tree.html
template< typename Monoid >
struct SegmentTree {
    using F = function< Monoid(Monoid, Monoid) >;

    int sz;
    vector< Monoid > seg;

    const F f;
    const Monoid M1;

    SegmentTree(int n, const F f, const Monoid& M1) : f(f), M1(M1) {
        sz = 1;
        while (sz < n) sz <<= 1;
        seg.assign(2 * sz + 1, M1);
    }

    void set(int k, const Monoid& x) {
        seg[k + sz] = x;
    }

    void build() {
        for (int k = sz - 1; k > 0; k--) {
            seg[k] = f(seg[2 * k + 0], seg[2 * k + 1]);
        }
    }

    void update(int k, const Monoid& x) {
        k += sz;
        seg[k] = x;
        while (k >>= 1) {
            seg[k] = f(seg[2 * k + 0], seg[2 * k + 1]);
        }
    }

    Monoid query(int a, int b) {
        Monoid L = M1, R = M1;
        for (a += sz, b += sz; a < b; a >>= 1, b >>= 1) {
            if (a & 1) L = f(L, seg[a++]);
            if (b & 1) R = f(seg[--b], R);
        }
        return f(L, R);
    }

    Monoid operator[](const int& k) const {
        return seg[k + sz];
    }

    template< typename C >
    int find_subtree(int a, const C& check, Monoid& M, bool type) {
        while (a < sz) {
            Monoid nxt = type ? f(seg[2 * a + type], M) : f(M, seg[2 * a + type]);
            if (check(nxt)) a = 2 * a + type;
            else M = nxt, a = 2 * a + 1 - type;
        }
        return a - sz;
    }


    template< typename C >
    int find_first(int a, const C& check) {
        Monoid L = M1;
        if (a <= 0) {
            if (check(f(L, seg[1]))) return find_subtree(1, check, L, false);
            return -1;
        }
        int b = sz;
        for (a += sz, b += sz; a < b; a >>= 1, b >>= 1) {
            if (a & 1) {
                Monoid nxt = f(L, seg[a]);
                if (check(nxt)) return find_subtree(a, check, L, false);
                L = nxt;
                ++a;
            }
        }
        return -1;
    }

    template< typename C >
    int find_last(int b, const C& check) {
        Monoid R = M1;
        if (b >= sz) {
            if (check(f(seg[1], R))) return find_subtree(1, check, R, true);
            return -1;
        }
        int a = sz;
        for (b += sz; a < b; a >>= 1, b >>= 1) {
            if (b & 1) {
                Monoid nxt = f(seg[--b], R);
                if (check(nxt)) return find_subtree(b, check, R, true);
                R = nxt;
            }
        }
        return -1;
    }
};

unsigned long xor128() {
    static unsigned long x = 123456789, y = 362436069, z = 521288629, w = 88675123;
    unsigned long t = (x ^ (x << 11));
    x = y; y = z; z = w;
    return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)));
}

void init() {
    iostream::sync_with_stdio(false);
    cin.tie(0);
}

#define int ll
void solve(){
    while (true) {
        int n;
        cin >> n;
        if (n == 0) return;
        vector<vector<int>> vertexs;
        REP(i, n) {
            int a[3];
            REP(q, 3) {
                cin >> a[q];
            }
            vector<int> tmp;
            sort(a, a + 3);
            do {
                REP(q, 60) {
                    a[0]++;
                    a[1]++;
                    a[2]++;
                    a[0] %= 60;
                    a[1] %= 60;
                    a[2] %= 60;
                    int s = a[0];
                    int m = a[1];
                    int h = a[2];
                    if (h % 5 != m / 12) continue;
                    h /= 5;
                    tmp.push_back(h * 3600 + m * 60 + s);
                }
            } while (next_permutation(a, a + 3));
            sort(ALL(tmp));
            tmp.erase(std::unique(tmp.begin(), tmp.end()), tmp.end());
            vertexs.push_back(tmp);
        }
        pair<int, int> ans(0, 1e9);
        REP(i, 60 * 60 * 12) {
            int ok = 1;
            int ending = 0;
            REP(q, n) {
                auto x = lower_bound(ALL(vertexs[q]), i);
                if (x == vertexs[q].end()) {
                    ok = 0;
                    break;
                }
                ending = max(ending, *x);
            }
            if (ok == 0) continue;
            if (ans.second - ans.first > ending - i) {
                ans = mp(i, ending);
            }
        }
        auto output = [](int a) {
            int hoge = a / 3600;
            if (hoge < 10) {
                cout << "0";
            }
            cout << hoge;
            cout << ":";
            a %= 3600;
            hoge = a / 60;
            if (hoge < 10) {
                cout << "0";
            }
            cout << hoge;
            cout << ":";
            a %= 60;
            hoge = a;
            if (hoge < 10) {
                cout << "0";
            }
            cout << hoge;
        };
        output(ans.first);
        cout << " ";
        output(ans.second);
        cout << endl;
    }
}
#undef int
int main() {
    init();
    solve();
}
accuracy: 1
time_ms: 60
memory_kb: 3040
final_rank: 2

code_snippet: #include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<complex>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<utility>
using namespace std;
typedef long long ll;
typedef unsigned long long ul;
typedef unsigned int ui;
typedef long double ld;
typedef pair<int, int> P;
typedef pair<ll, ll> LP;
typedef pair<ld, ld> LDP;
typedef complex<ld> Point;
const ll mod = 1000000007;
const ll INF = mod * mod;
const ld eps = 1e-8;
const ld pi = acos(-1.0);
#define stop char nyaa;cin>>nyaa;
#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define Rep1(i,sta,n) for(int i=sta;i<=n;i++)
int n;
int a[10][3];
int c[10];

bool ok() {
	rep(j, n) {
		if (c[j] == 0)return false;
	}
	return true;
}
bool exi[43200][10];

void output_as_time(int x) {
	string s;
	if (x / 3600 < 10)s += "0";
	s += to_string(x/3600);
	s.push_back(':');
	x %= 3600;
	if (x / 60 < 10)s += "0";
	s += to_string(x / 60);
	s.push_back(':');
	x %= 60;
	if (x < 10)s += "0";
	s += to_string(x);
	cout << s;
}
void solve() {
	while (cin >> n, n) {
		rep(i, 43200) {
			rep(j, n) {
				exi[i][j] = false;
			}
		}
		fill(c, c + n, 0);
		rep(i, n) {
			rep(j, 3) {
				cin >> a[i][j];
			}
		}
		rep(i, n) {
			rep(j, 60) {
				vector<int> v;
				rep(k, 3) {
					v.push_back((a[i][k]+j) % 60);
				}
				sort(v.begin(), v.end());
				while (true) {
					if (v[0] % 5 == v[1] / 12) {
						int sum = (v[0] / 5) * 3600 + v[1] * 60 + v[2];
						exi[sum][i] = true;
					}
					if (!next_permutation(v.begin(), v.end()))break;
				}
			}
		}
		int mi = 50000; int le = 0;
		int ri = 0;
		rep(i, 43200) {
			while (true) {
				if (ok())break;
				if (ri ==43200)break;
				rep(j, n) {
					if (exi[ri][j])c[j]++;
				}
				ri++;
			}
			if (!ok())break;
			if (ri - i < mi) {
				mi = ri - i; le = i;
			}
			rep(j, n) {
				if (exi[i][j])c[j]--;
			}
		}
		output_as_time(le);
		cout << " ";
		output_as_time(le + mi-1);
		cout << endl;
	}
}
int main() {
	solve();
	//stop
	return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3652
final_rank: 11

code_snippet: #include<bits/stdc++.h>
using namespace std;

bool isValid(vector<int> t){
    return t[0]%5==t[1]/12;
}

int calc(vector<int> t){
    return (t[0]/5)*60*60+t[1]*60+t[2];
}

void output(int t){
    cout<<setw(2);
    cout<<setfill('0');
    cout<<(t/3600)<<":";
    cout<<setw(2);
    cout<<setfill('0');
    cout<<(t/60%60)<<":";
    cout<<setw(2);
    cout<<setfill('0');
    cout<<(t%60);
}
int solve(int n){
    vector<vector<int>> t(n,vector<int>(3));
    for(int i=0;i<n;i++){
        for(int j=0;j<3;j++){
            cin>>t[i][j];
        }
    }

    vector<vector<int>> cand(n);
    for(int i=0;i<n;i++){
        for(int k=0;k<60;k++){
            for(int j=0;j<3;j++) t[i][j]=(t[i][j]+1)%60;
            for(int j=0;j<6;j++){
                if(isValid(t[i])){
                    cand[i].push_back(calc(t[i]));
                    cand[i].push_back(calc(t[i])+12*60*60);
                }
                next_permutation(t[i].begin(),t[i].end());
            }
        }
        cand[i].push_back(1e8);
        sort(cand[i].begin(),cand[i].end());
    }
    pair<int,int> res={1e8,1e8};
    for(int i=0;i<24*60*60;i++){
        int till=0;
        for(int j=0;j<n;j++){
            till=max(till,*lower_bound(cand[j].begin(),cand[j].end(),i));
        }
        res=min(res,{till-i,i});
    }
    output(res.second);
    cout<<" ";
    output(res.first+res.second);
    cout<<endl;
}

int main(){
    int n;
    while(cin>>n,n){
        solve(n);
    }
    return 0;
}
accuracy: 1
time_ms: 130
memory_kb: 3124
final_rank: 4

code_snippet: // g++ -std=c++11 a.cpp
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>	
#include<map>
#include<set>
#include<unordered_map>
#include<utility>
#include<cmath>
#include<random>
#include<cstring>
#include<queue>
#include<stack>
#include<bitset>
#include<cstdio>
#include<sstream>
#include<iomanip>
#include<assert.h>
#include<typeinfo>
#define loop(i,a,b) for(int i=a;i<b;i++) 
#define rep(i,a) loop(i,0,a)
#define FOR(i,a) for(auto i:a)
#define pb push_back
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)
#define show1d(v) rep(_,v.size())cout<<" "<<v[_];cout<<endl;
#define show2d(v) rep(_,v.size()){rep(__,v[_].size())cout<<" "<<v[_][__];cout<<endl;}cout<<endl;
using namespace std;
//kaewasuretyuui
typedef long long ll;
#define int ll
typedef int Def;
typedef pair<Def,Def> pii;
typedef vector<Def> vi;
typedef vector<vi> vvi;
typedef vector<pii> vp;
typedef vector<vp> vvp;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef pair<Def,pii> pip;
typedef vector<pip>vip;
#define mt make_tuple
typedef tuple<int,int,int,int> tp;
typedef vector<tp> vt;
template<typename A,typename B>bool cmin(A &a,const B &b){return a>b?(a=b,true):false;}
template<typename A,typename B>bool cmax(A &a,const B &b){return a<b?(a=b,true):false;}
//template<class C>constexpr int size(const C &c){return (int)c.size();}
//template<class T,size_t N> constexpr int size(const T (&xs)[N])noexcept{return (int)N;}
const double PI=acos(-1);
const double EPS=1e-9;
Def inf = sizeof(Def) == sizeof(long long) ? 1e18+10 : 1e9+10;
int dx[]={0,1,0,-1,1,1,-1,-1};
int dy[]={1,0,-1,0,1,-1,1,-1};//RDLU
//09062355704
int f(int a,int b,int c){
	int out=b*60+c;
	a-=b/12;
	if(a<0)a+=60;
	if(a%5)return -1;
	out+=a/5*3600;
	return out;
}
signed main(){
	int n;
	while(cin>>n,n){
		vvi in(n,vi(3));
		rep(i,n)rep(j,3)cin>>in[i][j];
		vi dp(43200,-inf);
		rep(i,n){
			vi t;
			rep(j,60){
				sort(all(in[i]));
				do{
					int a=f(in[i][0],in[i][1],in[i][2]);
					if(a+1)t.pb(a);
				}while(next_permutation(all(in[i])));
				rep(k,3)(in[i][k]+=1)%=60;
			}
//			show1d(t);
			vi ndp(43200,-inf);
			rep(j,43200)rep(k,t.size())if(i==0||dp[j]+inf){
				if(i==0){
					ndp[t[k]]=t[k];
					continue;
				}
				int mi=dp[j],ma=j;
				cmin(mi,t[k]);
				cmax(ma,t[k]);
				cmax(ndp[ma],mi);
			}
			dp=ndp;
		}
		int mi=inf,it;
		rep(i,43200)if(mi>i-dp[i]){
			mi=i-dp[i];
			it=i;
		}
		printf("%02d:%02d:%02d %02d:%02d:%02d\n",dp[it]/3600,dp[it]%3600/60,dp[it]%60,it/3600,it%3600/60,it%60);
	}
}
accuracy: 1
time_ms: 250
memory_kb: 3808
final_rank: 12

code_snippet: #include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<unordered_map>
#include<utility>
#include<cmath>
#include<random>
#include<cstring>
#include<queue>
#include<stack>
#include<bitset>
#include<cstdio>
#include<sstream>
#include<iomanip>
#include<assert.h>
#include<typeinfo>
#define loop(i,a,b) for(int i=a;i<b;i++)
#define rep(i,a) loop(i,0,a)
#define FOR(i,a) for(auto i:a)
#define pb push_back
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)
#define show1d(v) rep(_,v.size())cout<<" "<<v[_];cout<<endl;
#define show2d(v) rep(_,v.size()){rep(__,v[_].size())cout<<" "<<v[_][__];cout<<endl;}cout<<endl;
using namespace std;
//kaewasuretyuui
typedef long long ll;
#define int ll
typedef int Def;
typedef pair<Def,Def> pii;
typedef vector<Def> vi;
typedef vector<vi> vvi;
typedef vector<pii> vp;
typedef vector<vp> vvp;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef pair<Def,pii> pip;
typedef vector<pip>vip;
//#define mt make_tuple
//typedef tuple<int,int,int,int> tp;
//typedef vector<tp> vt;
template<typename A,typename B>bool cmin(A &a,const B &b){return a>b?(a=b,true):false;}
template<typename A,typename B>bool cmax(A &a,const B &b){return a<b?(a=b,true):false;}
//template<class C>constexpr int size(const C &c){return (int)c.size();}
//template<class T,size_t N> constexpr int size(const T (&xs)[N])noexcept{return (int)N;}
const double PI=acos(-1);
const double EPS=1e-9;
Def inf = sizeof(Def) == sizeof(long long) ? 1e18+10 : 1e9+10;
int dx[]={0,1,0,-1,1,1,-1,-1};
int dy[]={1,0,-1,0,1,-1,1,-1};//RDLU
//09062355704
int f(int a,int b,int c){
    int out=b*60+c;
    a-=b/12;
    if(a<0)a+=60;
    if(a%5)return -1;
    out+=a/5*3600;
    return out;
}
signed main(){
    int n;
    while(cin>>n,n){
        vvi in(n,vi(3));
        rep(i,n)rep(j,3)cin>>in[i][j];
        vi dp(43200,-inf);
        rep(i,n){
            vi t;
            rep(j,60){
                sort(all(in[i]));
                do{
                    int a=f(in[i][0],in[i][1],in[i][2]);
                    if(a+1)t.pb(a);
                }while(next_permutation(all(in[i])));
                rep(k,3)(in[i][k]+=1)%=60;
            }
          //show1d(t);
            vi ndp(43200,-inf);
            rep(j,43200)rep(k,t.size())if(i==0||dp[j]+inf){
                if(i==0){
                    ndp[t[k]]=t[k];
                    continue;
                }
                int mi=dp[j],ma=j;
                cmin(mi,t[k]);
                cmax(ma,t[k]);
                cmax(ndp[ma],mi);
            }
            dp=ndp;
        }
        int mi=inf,it;
        rep(i,43200)if(mi>i-dp[i]){
            mi=i-dp[i];
            it=i;
        }
//      cout<<it<<" "<<dp[it]<<endl;
        printf("%02d:%02d:%02d %02d:%02d:%02d\n",dp[it]/3600,dp[it]%3600/60,dp[it]%60,it/3600,it%3600/60,it%60);
    }
}
accuracy: 1
time_ms: 250
memory_kb: 3808
final_rank: 12

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cassert>
#include <cstring>
using namespace std;

const int TM_MAX = 44000;

bool is_valid_time(vector<int> vec) {
    for(int i=0; i<3; i++) {
        vec[i] %= 60;
    }

    int h = vec[0], m = vec[1];
    int tick = h % 5;
    int lb = 12 * tick, ub = 12 * (tick + 1);
    return lb <= m && m < ub;
}

int calc_time(vector<int> vec) {
    for(int i=0; i<3; i++) {
        vec[i] %= 60;
    }
    vec[0] = vec[0] / 5 * 5;
    return vec[0] * 60 * 12 + vec[1] * 60 + vec[2];
}

struct Segment {
    int l, r, len;
    Segment() {}
    Segment(int x, int y) {
        assert(x <= y);
        l = x, r = y;
        len = r - l + 1;
    }
    bool operator<(const Segment &s) const {
        if(len != s.len) return len < s.len;
        return l < s.l;
    }
};

string convert_time(int tm) {
    int h = (tm / 3600) % 12;
    int m = (tm / 60) % 60;
    int s = tm % 60;

    char buf[30];
    sprintf(buf, "%02d:%02d:%02d", h, m, s);

    return string(buf);
}

string convert_seg(Segment s) {
    string ret = "";
    ret += convert_time(s.l) + " ";
    ret += convert_time(s.r);
    return ret;
}

int main() {
    int N;
    while(cin >> N, N) {
        vector<int> watch_list[TM_MAX];
        for(int i=0; i<N; i++) {
            vector<int> times(3);
            for(int k=0; k<3; k++) {
                cin >> times[k];
            }

            sort(times.begin(), times.end());
            do {
                for(int k=0; k<60; k++) {
                    vector<int> tmp = times;
                    for(int x=0; x<3; x++) tmp[x] += k;

                    if(!is_valid_time(tmp)) continue;

                    int point = calc_time(tmp);
                    watch_list[point].push_back(i);
                }
            }while(next_permutation(times.begin(), times.end()));
        }

        int cnt = 0;
        vector<int> appeared(N);

        int ub = 0, lb = 0;
        vector<Segment> seg;
        while(ub < TM_MAX) {
            for(; ub < TM_MAX && cnt != N; ub++) {
                for(auto x : watch_list[ub]) {
                    if(appeared[x] == 0) cnt++;
                    appeared[x]++;
                }
            }

            for(; cnt == N; lb++) {
                for(auto x : watch_list[lb]) {
                    if(appeared[x] == 1) cnt--;
                    appeared[x]--;
                }
            }

            if(ub != TM_MAX) {
                seg.push_back(Segment(lb - 1, ub - 1));
            }
        }

        sort(seg.begin(), seg.end());
        cout << convert_seg(seg[0]) << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 4200
final_rank: 16