We are told: "Create a program that takes n words as input, determines whether or not a shiritori can be created from those word pairs, and outputs OK if possible and NG if not."
We need to interpret the problem: We are given n words. We need to arrange all words in some order (use all words exactly once) to form a shiritori chain: for consecutive words, the last character of the previous word equals the first character of the next word. Additionally, the first character of the first word must equal the last character of the last word (forming a cycle). So it's a Hamiltonian cycle in a directed graph where vertices are words, and an edge from word i to word j exists if last_char(i) == first_char(j). But note that words can be repeated? Possibly there could be duplicate words? The input says words are given, but nothing says they are distinct? Typically they could be distinct, but we should consider duplicates as separate nodes? In shiritori, each word is used exactly once, duplicates are separate tokens, but they are identical strings. However, they are considered distinct occurrences. So we have n nodes (with labels including first and last letters). The question: can we arrange all nodes in a cyclic order such that each consecutive pair satisfies last_i = first_j, and also last of last = first of first. That's essentially finding a directed Eulerian trail? Wait careful: We need a permutation of the nodes that forms a Hamiltonian cycle. However, n can be up to 10000, and number of datasets up to 50. Checking Hamiltonian cycle in directed graph is NP-hard in general. But there is likely a simpler condition based on counts of first and last letters. Because the words are just strings, and we only care about first and last characters. This is reminiscent of arranging words into a cycle if we consider each word as an edge from its first character to its last character. Then arranging words in order corresponds to concatenating edges to form a Eulerian trail in a multigraph where vertices are letters (lowercase 'a' to 'z') and each word is a directed edge from its first letter to its last letter. Indeed, if we consider each word as a directed edge from its first character (f) to its last character (l), then a sequence of words (w1, w2, ..., wn) such that last of wi equals first of w_{i+1} corresponds to a walk that follows these edges in order. If we also require that the last word's last character equals the first word's first character, then the walk is a closed trail that starts and ends at the same vertex, using each edge exactly once. That's exactly a Eulerian circuit in the directed multigraph (where vertices are 26 letters). So the problem reduces to: Given a multiset of directed edges (from first letter to last letter) on the vertex set of 26 letters, does there exist an Eulerian circuit that uses every edge exactly once? But careful: In a Eulerian circuit, edges are used exactly once and the sequence of edges forms a trail (no repeated edges but can repeat vertices). That corresponds exactly to a shiritori arrangement where words follow the condition and the cycle condition. However, does an Eulerian circuit guarantee that the arrangement of words is possible? In the Eulerian circuit, the order of edges yields a sequence of words that satisfies the condition, but we need to assign specific words to edges. Since edges are distinguished by their word identity, any Eulerian circuit gives an ordering of the edges satisfying the constraints. However, there is a nuance: In a Eulerian circuit, consecutive edges must share the vertex: end of edge i equals start of edge i+1. That's exactly the shiritori condition. Also the start vertex of the first edge equals the end vertex of the last edge, which is the cycle condition. So yes, an Eulerian circuit corresponds to a valid shiritori ordering. Conversely, any valid ordering of words yields a closed trail using each edge exactly once, so it is an Eulerian circuit. Thus the problem is equivalent to checking if the directed multigraph (on 26 vertices) has an Eulerian circuit.
Wait: Are there any additional constraints? The words have strings, but the actual content besides first and last letters is irrelevant. The condition only uses first and last characters. So indeed, this is exactly Eulerian circuit existence.
But wait: The problem description: "use all the words to make a shiritori in order, and then the first letter of the first word and the last letter of the last word are the same." That's exactly a cyclic shiritori using all words. So we need to check if we can order them accordingly. This is classic: The necessary and sufficient conditions for a directed graph to have an Eulerian circuit are:
- The graph is connected when considering vertices with nonzero degree (i.e., all edges belong to a single weakly connected component).
- For every vertex, in-degree equals out-degree.
But careful: For directed graphs, the condition for Eulerian circuit is: The underlying undirected graph is connected (ignoring isolated vertices) and for each vertex, indegree equals outdegree. However, there is also a nuance about "weakly connected" meaning the graph when considered as undirected is connected across all vertices with edges. But there could be vertices with zero degree. So we need to check these conditions.
But also note: The graph has up to 10000 edges, 26 vertices, so it's manageable.
Now the input format: multiple datasets until 0. For each dataset, n, then n words. Output "OK" if possible, else "NG".
But we must be careful: Is it exactly Eulerian circuit? Let's think about the interpretation: We have to arrange the words themselves. If we treat each word as an edge, the Eulerian circuit ordering uses each edge exactly once. That yields a sequence of words where each consecutive pair matches (last char of previous = first char of next). And the cycle condition: start of first = end of last? In an Eulerian circuit, we start at some vertex v, follow edges, and end at v. The start vertex of the first edge is v, the end vertex of the last edge is v, so condition holds: first letter of first word (v) equals last letter of last word (v). So it's satisfied.
Thus condition reduces to indegree=outdegree for all vertices and the graph of used vertices is connected (weakly). However, note that if the graph has multiple components but each component has balanced indegree/outdegree, can we still form a single cycle using all edges? No, because to traverse all edges without lifting the pen, the graph must be connected (weakly). So that's necessary.
But wait: In directed Eulerian circuits, connectivity is required in the underlying undirected graph for the whole graph (ignoring isolated vertices). But there's also a condition about "all vertices with nonzero degree belong to a single strongly connected component"? Actually, for Eulerian circuit in directed graph, it's required that the graph is "strongly connected" when considering vertices with nonzero degree? Let's recall standard theorem: A directed graph has an Eulerian circuit if and only if every vertex has equal indegree and outdegree, and all vertices with nonzero degree belong to a single strongly connected component of the graph. However, some formulations state that the graph must be weakly connected and each vertex's indegree equals outdegree. But is strong connectivity automatically implied by indegree=outdegree and weak connectivity? Not necessarily: Consider a graph with vertices A and B, edges: A->B and B->A. That's strongly connected. That's fine. But consider a graph with vertices A, B, C: edges A->B, B->A, and C->C? That would have weak connectivity? Actually, if C has a loop and is isolated from A-B component, then weak connectivity fails because there's no undirected path from C to A (if C has a loop but no edge to others, then it's isolated). So weak connectivity ensures all vertices with degree > 0 are in one component. But what about a graph that is weakly connected but not strongly? Example: Two vertices A and B with edges A->B and A->B (multiple edges) but no edge from B to A. Indegree(A)=0, outdegree(A)=2; indegree(B)=2, outdegree(B)=0. Not balanced. So indegree/outdegree condition would fail. To get balanced but not strongly connected, we need each vertex indegree=outdegree, but weak connectivity might allow a graph that is not strongly connected? Let's try: Consider vertices A, B, C. Edges: A->B, B->C, C->A. That's a cycle, strongly connected. Another example: Two cycles that intersect at a vertex? That is strongly connected. Actually, if every vertex has indegree=outdegree >0, and the graph is weakly connected, does it guarantee strong connectivity? Not always: Consider a graph with vertices A, B, C, D. Edges: A->B, B->A (forming a strongly connected component), and C->D, D->C (another SCC), plus maybe an edge from A to C? That would connect them. If we add an edge from A to C, then indegree of C increases by 1, outdegree of A increases by 1. To keep balance, we need also an edge from somewhere to A or from C to something else? Let's try to construct a weakly connected graph where indegree=outdegree for all vertices but it's not strongly connected. For strong connectivity, every vertex must be reachable from every other vertex. Could we have a graph that is weakly connected and balanced but not strongly connected? Suppose we have two strongly connected components that are connected by a single edge. But if there's a directed edge from component X to Y, then to satisfy indegree=outdegree, there must be a path back? Actually, the condition for Eulerian circuit is indeed that all vertices with nonzero degree belong to a single strongly connected component of the graph. Because consider an Eulerian circuit: starting at a vertex, you can traverse the entire graph, meaning you can go from any vertex to any other following the Eulerian trail, so the graph must be strongly connected (when considering vertices with edges). However, the theorem states: A directed graph has an Eulerian circuit iff each vertex has indegree=outdegree and the graph is "weakly connected" and "all vertices with nonzero degree belong to a single strongly connected component of the graph"? I'm trying to recall precisely.
Let's consider a known counterexample: A directed graph with vertices A and B: edges A->B and B->A, that's strongly connected. Balanced. Another: A->B, B->C, C->B, B->A? Let's think. I recall standard condition: For a directed graph to have an Eulerian circuit, it must be strongly connected when considering vertices with nonzero degree, and indegree=outdegree for all vertices. However, the condition of strong connectivity is actually implied by indegree=outdegree plus weak connectivity? Let's check: Suppose we have a graph that is weakly connected but not strongly connected. Since indegree=outdegree, the total flow is balanced. Could it still be Eulerian? I think not. Consider two cycles that share a vertex? That would be strongly connected because from any vertex you can reach the shared vertex and then go to any other? Actually if two cycles share a vertex, the graph is strongly connected because from any vertex in one cycle you can go to the shared vertex and then into the other cycle. So that's strongly connected.
Consider a graph with vertices A, B, C. Edges: A->B, B->A (so A and B form a 2-cycle). Also edges: A->C, C->A? That would be strongly connected. To break strong connectivity, we need a situation where there is a directed edge from one SCC to another but no return path. But if there is such an edge, then indegree/outdegree might be unbalanced? Let's try: Suppose we have two SCCs: X and Y, and there is a directed edge from vertex u in X to vertex v in Y. For Eulerian circuit, if you ever go from X to Y via that edge, you must eventually return to X to complete the circuit. But to return, there must be a directed path from Y to X. Otherwise, you would be stuck in Y and cannot go back to start. However, the existence of an Eulerian circuit would imply that such a path exists. So strong connectivity is required. Conversely, if the graph is weakly connected and every vertex has indegree=outdegree, could it still not be strongly connected? I think yes, there exist weakly connected directed graphs where each vertex has indegree=outdegree but the graph is not strongly connected. Example: Consider vertices A, B, C. Edges: A->B, B->A (a cycle). Also edges: A->C, C->A? That would be strong. Not yet.
Maybe a simpler example: A graph with two vertices A and B, and two edges: A->B and A->B (multiple edges) and two edges: B->A and B->A. That's balanced and strongly connected? Actually from A to B we have edges, from B to A we have edges, so it's strongly connected. Balanced.
To get a weakly connected but not strongly connected graph, we need a vertex that can be reached from another but not vice versa. For indegree=outdegree to hold, if there is an edge from u to v, then to balance the flow, there must be some edge(s) that bring flow back to u from v? Not necessarily, because indegree and outdegree are local; u could have outdegree greater than indegree if there is a compensating path? But indegree=outdegree must hold exactly at each vertex. So if u has an extra out-edge to v, then u's outdegree is one more than indegree unless balanced by an extra in-edge from somewhere else. Similarly, v's indegree would be one more than outdegree unless balanced by an extra out-edge. So to correct the imbalance, we need extra edges that could create a return path. But it might be possible to have two vertices A and B such that there is a directed edge from A to B, and also an edge from B to A, then both are balanced if that's the only edges? Actually, if we have A->B and B->A, then indegree(A)=1, outdegree(A)=1; indegree(B)=1, outdegree(B)=1. Balanced, and strongly connected. To have weak connectivity but not strong, we need a third vertex C that is reachable from A but not back. For example, edges: A->B, B->A (balance A,B). Also A->C, C->A? That would be strong. If we instead have A->C and C->C (a loop) but no edge from C to A? Then indegree(C): from A (1) + from itself (1 if loop counts as both in and out? Actually, a loop contributes 1 to both indegree and outdegree of C. So indegree(C)=2, outdegree(C)=1 (if only loop? Wait loop adds 1 to indegree and 1 to outdegree). So if we have A->C and a loop C->C, then indegree(C)=2 (from A and from itself), outdegree(C)=1 (just the loop? Actually the loop is an outgoing edge, but does it count as outdegree? Yes, it is an edge from C to C, so outdegree incremented by 1. So outdegree(C)=1, indegree(C)=2, imbalance. To balance, we need another outgoing edge from C, maybe C->A? That would be return. So again strong.
Let's try to build a known example: a graph that is weakly connected, each vertex indegree=outdegree, but not strongly connected. I recall that for directed graphs, weak connectivity plus balance does not guarantee strong connectivity. But I'm trying to recall standard results: For Eulerian circuit, the condition is that the graph is "weakly connected" and each vertex has indegree=outdegree, provided that we ignore vertices with degree zero. Actually, some sources state that for a directed graph to have an Eulerian circuit, it must be "strongly connected" when considering vertices with at least one edge. However, I'm not entirely sure. Let's think: In an undirected graph, Eulerian circuit condition is connectivity and even degree. For directed, the condition is that the graph is "weakly connected" and each vertex's indegree equals outdegree. But is strong connectivity automatically implied? Consider a directed graph that is a single directed cycle: that's strongly connected. If the graph has multiple cycles intersecting, still strongly connected if there's a way to go from any vertex to any other following directed edges. Could there be a directed graph that is weakly connected and balanced but not strongly connected? I think it's impossible because if every vertex has equal indegree and outdegree, then the graph is "Eulerian" and must be strongly connected in the sense that for any two vertices with nonzero degree, there is a directed path between them. Actually, the existence of an Eulerian circuit itself implies that the graph is strongly connected (since the Eulerian circuit visits all edges, you can go from any vertex to any other by following the circuit). So strong connectivity is a necessary condition. But does the combination of weak connectivity and balance imply strong connectivity? I suspect yes for directed multigraphs where each vertex has total degree >0 and indegree=outdegree. Let's try to prove: Suppose we have a directed graph that is weakly connected and every vertex has indegree equal to outdegree. Then for any two vertices u and v, there is an undirected path. But does there have to be a directed path from u to v? Not necessarily: Consider a graph with vertices A, B, C, D. Edges: A->B, B->A (so A and B are strongly connected). Also edges: C->D, D->C (so C and D strongly connected). Plus two edges: B->C and D->A. Check indegree/outdegree: For A: indegree from B? Actually edges: A->B, B->A, D->A. So A's outdegree: 1 (to B), indegree: from B and D =2. Imbalance. Need to balance: maybe add a loop? Not good. Let's try to balance by adding edges appropriately. Suppose we want indegree=outdegree for all vertices. We have two components we want to connect with directed edges but keep balance. Let's attempt to construct a balanced weakly connected graph that is not strongly connected.
Let vertices: 1,2,3. Edges: 1->2, 2->1 (balanced for 1 and 2). Now we want to attach vertex 3 such that it's reachable from 1 or 2 but not both directions? But need balance for 3. Add edges: 1->3 and 3->1. That gives balanced for 1? Actually before adding, 1 had out=1, in=1 (balanced). After adding 1->3, out becomes 2; 1 gets indegree from 3? We add 3->1, so indegree becomes 2. So still balanced. 3 gets out=1 (to 1) and in=1 (from 1). Balanced. Graph becomes strongly connected (since 1,2,3 all connected). To break strong connectivity, we need a scenario where there is no directed path from 3 to 2 perhaps. But if we have edges 1->2 and 2->1, and edges 1->3 and 3->1, then from 3 you can go to 1 then to 2, so reachable. So strong.
What if we have edges: 1->2, 2->1, and 1->3, 3->3? That is, a loop on 3 and edge from 1 to 3. Then indegree/outdegree: 1: out (to2, to3)=2, in (from2)=1 -> imbalance. To balance 1, we need an extra incoming edge, maybe from 3 to 1. So that gives strong again.
Maybe the condition indegree=outdegree forces the graph to be strongly connected if it is weakly connected and has no isolated vertices. Actually, I think it's true that a directed graph is Eulerian (has Eulerian circuit) iff it is strongly connected (ignoring isolated vertices) and each vertex has indegree=outdegree. But some textbooks state weak connectivity plus balance. Let's check known results: In directed graphs, an Eulerian trail (not necessarily circuit) exists if at most one vertex has outdegree-indegree=1, at most one vertex has indegree-outdegree=1, and all others balanced, and the graph is weakly connected. For Eulerian circuit, it requires all vertices balanced and the graph is "weakly connected" and "all vertices with nonzero degree belong to a single strongly connected component"? Actually, I recall that for directed graphs, the condition for Eulerian circuit is that the graph is "weakly connected" and for every vertex, indegree equals outdegree. However, I'm aware of a subtlety: In directed graphs, connectivity for Eulerian circuits is often defined in terms of being "strongly connected" when considering vertices with nonzero degree. But is it automatically satisfied if indegree=outdegree and the graph is weakly connected? Let's search memory: In many programming contest problems about "arranging words into a chain or cycle", the condition is indegree=outdegree for all letters and the graph of letters (vertices) is connected (undirected). And they often treat it as Eulerian circuit in directed graph but they only check weak connectivity. I've seen problems like "POJ 1386 Play on Words" which asks if you can form a chain (not necessarily cycle) of words such that each word's first letter matches previous word's last letter, using all words exactly once. That's Eulerian path. The typical solution: build directed graph of letters; check indegree/outdegree conditions (at most one start and one end with difference 1, others equal) and the graph (ignoring isolated vertices) is weakly connected. For a cycle, the condition is all indegree=outdegree and the graph is weakly connected. That is the standard condition for a directed graph to have an Eulerian circuit, provided the graph is "weakly connected" and every vertex has indegree=outdegree. I think that's correct because if the graph is weakly connected and balanced, it is automatically strongly connected? Let's verify with a counterexample: Consider a directed graph with vertices A, B, C. Edges: A->B, B->A (a two-cycle). Also edges: B->C, C->B? That would be strong. To get not strong, we need a scenario where there is a directed edge from a component to another without a way back. But because of balance, the sum of outdegrees equals sum of indegrees globally. If there is a set S of vertices such that there are edges from S to complement but no edges from complement to S, then total outdegree of S > total indegree of S, contradicting balance if each vertex individually balanced? Actually, the condition for strong connectivity can be related to "balanced" condition: For any subset S of vertices, the number of edges leaving S must equal the number of edges entering S if every vertex in S has indegree=outdegree? Not exactly. If every vertex has indegree=outdegree, then for any subset S, sum of outdegrees over S equals sum of indegrees over S? Because sum out(S) - sum in(S) = 0? Let's compute: Sum_{v in S} out(v) - sum_{v in S} in(v) = 0. But that sum equals (edges from S to V\S) - (edges from V\S to S) (since internal edges cancel). So we have |edges(S -> V\S)| - |edges(V\S -> S)| = 0. Hence the net flow across the cut is zero. This implies |edges(S -> V\S)| = |edges(V\S -> S)|. So there are edges in both directions equally. In particular, if there is any edge from S to complement, there must be at least one edge from complement to S. However, does this guarantee strong connectivity? Not directly; it could be that the graph is composed of two strongly connected components that are mutually connected by edges in both directions. But if there are edges in both directions between components, then the whole graph becomes strongly connected because from a vertex in one component you can go to the other component via the forward edge, and then maybe you need to return to the original component via the backward edge, but to go from a vertex in second component to a vertex in first component you can use the backward edge? Actually, if there is at least one edge from S to complement and at least one edge from complement to S, then any vertex in S can reach any vertex in complement: from a vertex in S, you can go to some vertex in complement via a path? But you might need to reach the specific edge. If the graph consists of two strongly connected components (S and T) with at least one edge from S to T and at least one edge from T to S, then the whole graph is strongly connected? Let's check: Take two SCCs, each internally strongly connected. If there is an edge from S to T and an edge from T to S, then for any u in S and v in T: from u you can go within S to the vertex that has the outgoing edge to T (since S is strongly connected), then cross to T, then within T to v (since T is strongly connected). Similarly, from v in T to u in S: go within T to the vertex with edge to S, cross, then within S to u. Also for two vertices both in S, they are reachable via S's internal connectivity. So the whole graph becomes strongly connected. Therefore, if the graph is weakly connected and each SCC is maximal, the presence of edges in both directions between any two SCCs would merge them into a larger SCC. Thus the only way to have multiple SCCs is if there are no edges between them in either direction (so they are disconnected), or edges only in one direction? But if edges only in one direction from S to T, then the net flow condition would be violated because |edges(S->T)| would be positive while |edges(T->S)| would be zero, leading to sum out(S)-in(S) > 0, contradicting balance. However, balance condition is per vertex, not per subset. But we derived that for any subset S, the net flow is zero because sum(out(v)-in(v)) over S = 0, which is true if every vertex in S has out=in. So indeed, for any S, the number of edges from S to complement equals number from complement to S. Therefore, if there is any edge from S to complement, there must be at least one edge from complement to S. This implies that if the graph is weakly connected (meaning the underlying undirected graph is connected), then the directed graph must be strongly connected? Let's argue: Suppose the directed graph is not strongly connected. Then there exists a partition of vertices into two nonempty sets S and T such that there are no edges from S to T (or possibly no edges from T to S)? Actually, strong connectivity fails if there exists a pair of vertices u, v such that there is no directed path from u to v. This does not necessarily imply a cut with no edges in one direction; it's more complex. However, for finite directed graphs, if the graph is not strongly connected, then it can be decomposed into strongly connected components, and the condensation graph (DAG) has at least one edge between components in some direction. If there are at least two SCCs, then consider the set of SCCs with no incoming edges (sources) or no outgoing edges (sinks). In a DAG, there exist source SCCs with no incoming edges from other SCCs, and sink SCCs with no outgoing edges. If the condensation graph has more than one SCC, then there is at least one source SCC S that has no incoming edges from other SCCs (i.e., no edges from complement to S). Then edges from S to complement may exist or not. But if there is an edge from S to complement, then the net flow from S to complement is positive, while from complement to S is zero, violating the balance condition (since for set S, sum out - sum in = edges(S->complement) - edges(complement->S) > 0). But if there is no edge from S to complement either, then S is isolated, meaning the graph is not weakly connected (since no undirected connection to the rest). So if the graph is weakly connected and balanced, there cannot be a source SCC with no incoming edges, because that would violate balance or connectivity. Similarly for sink SCCs. Therefore, all SCCs must have both incoming and outgoing edges, which forces the condensation graph to be strongly connected? Actually, if every SCC has at least one incoming edge from other SCCs and at least one outgoing edge to other SCCs, then the condensation graph is strongly connected? Not necessarily; consider a directed cycle of SCCs: that is strongly connected in the condensation graph? A directed cycle is strongly connected as a directed graph? A directed cycle of multiple nodes is strongly connected because you can go from any node to any other by following the cycle direction. Indeed, a directed graph that is a cycle (i.e., 1->2,2->3,...,k->1) is strongly connected. For the condensation graph to be a DAG, having every node with indegree>=1 and outdegree>=1 does not guarantee strong connectivity. For example, consider two nodes A and B with edges A->B and B->A (both directions) - that's strongly connected. But could we have a graph with three SCCs where each has both in and out but still not strongly connected? Suppose SCC1 has edges to SCC2, SCC2 has edges to SCC3, and SCC3 has edges to SCC1? That's a cycle, strongly connected. Suppose SCC1 has edges to SCC2, SCC2 has edges to SCC1, and also SCC1 has edges to SCC3 and SCC3 has edges to SCC2? That might still be strongly connected? Actually, if the condensation graph is a DAG, by definition it has no directed cycles. If there is a node with indegree>=1 and outdegree>=1, that doesn't create a cycle necessarily. For instance, consider three nodes: A -> B, A -> C, B -> C. This DAG has A source? Actually A has indegree 0? Let's set up: Nodes: X, Y, Z. Edges: X->Y, X->Z, Y->Z. Here X has indegree 0, so it's a source. So not both in and out. To have all nodes with indegree>=1 and outdegree>=1 in a DAG is impossible because in a DAG there must be at least one source (indegree 0) and at least one sink (outdegree 0). Therefore, if every SCC has indegree>=1 and outdegree>=1, the condensation graph cannot be a DAG; it must contain a directed cycle, implying strong connectivity of the condensation graph? Wait, if condensation graph contains a directed cycle, then the SCCs in that cycle can be merged into a larger SCC because if there is a directed edge from SCC A to SCC B and from B to A, then A and B are actually mutually reachable? Actually by definition, SCCs are maximal strongly connected components, so there cannot be a directed cycle between distinct SCCs because if there is a path from A to B and from B to A, then they belong to the same SCC. So the condensation graph is always a DAG (no directed cycles). Thus it's impossible for the condensation graph to have a directed cycle. Therefore, in a DAG, there must exist at least one source (indegree 0) and at least one sink (outdegree 0). So if the original directed graph has more than one SCC, there will be at least one source SCC with no incoming edges from other SCCs, and at least one sink SCC with no outgoing edges to other SCCs. For a source SCC S, there are no edges from complement to S. If there is at least one edge from S to complement, then for the set S, edges(S->complement) > 0 and edges(complement->S)=0, so sum out(S)-in(S) > 0. But if each vertex in S has indegree=outdegree, then sum(out(S)) = sum(in(S)). However, in(S) includes internal edges within S and edges from complement to S. Since no edges from complement to S, in(S) only includes internal edges, but out(S) includes internal edges plus edges from S to complement. Internal edges cancel out in the sum out(S)-in(S) because each internal edge contributes 1 to out of some vertex in S and 1 to in of some (possibly same) vertex in S. So sum(out(S)) - sum(in(S)) = number of edges from S to complement - number of edges from complement to S. If latter is zero and former positive, the sum is positive, contradicting the fact that each vertex in S has out=in (so sum difference zero). Therefore, to avoid contradiction, either there are no edges from S to complement either. But then S is isolated from the rest (no edges between S and complement), which would mean the graph is not weakly connected. Hence, if the graph is weakly connected and each vertex has indegree=outdegree, there cannot be more than one SCC. So the graph must be strongly connected. So indeed weak connectivity + balance implies strong connectivity (for vertices with nonzero degree). Therefore, checking weak connectivity and balance is sufficient.
Thus the problem reduces to: For the directed multigraph on 26 vertices (letters 'a'..'z'), with edges defined by each word (first char -> last char), check if:
- For each vertex, indegree == outdegree.
- The graph (considering vertices that appear in any edge) is weakly connected (i.e., the underlying undirected graph is connected).
If both hold, output "OK", else "NG".
But wait: Is there any nuance about words that start and end with the same letter? That creates a loop edge (self-loop). In Eulerian circuit, self-loops are allowed and they contribute 1 to both indegree and outdegree of that vertex. Also connectivity: a vertex with a self-loop is considered to have degree, so it's part of the graph. Self-loops do not affect connectivity across vertices; they are still within the same vertex. But if the graph only has loops on a single vertex and no other vertices, then it's trivially connected (only one vertex). However, if there are multiple vertices but only loops, there is no connection between them, so graph would be disconnected. So we must consider undirected connectivity: an edge from u to v (including u=v) connects u and v in the undirected sense (even a loop doesn't connect to other vertices). For connectivity, we treat each edge as connecting its endpoints in an undirected way; a loop only connects the vertex to itself, so it doesn't help connect different vertices. So we need to ensure that the underlying undirected graph (where each directed edge becomes an undirected edge between its start and end vertices) is connected, ignoring isolated vertices (those with no incident edges). That means that all vertices that have any incident edge (either indegree>0 or outdegree>0) must belong to a single connected component when considering undirected edges.
Thus we can implement:
- For each dataset:
- Initialize arrays in[26], out[26] to 0.
- Also an adjacency list for undirected connectivity: for each edge (first, last), union the two letters (if first != last, add undirected edge; if first == last, it's a loop, but loops don't connect to other vertices; we can still treat the vertex as having degree, but for connectivity we need to ensure that vertices with loops are not isolated if they are alone? Actually if all words are loops on the same vertex, then the graph has one vertex (with loops) and is considered connected (only one vertex). If there are loops on multiple distinct vertices but no edges between them, then the graph has multiple components (each vertex with loops is isolated from others). So we need to detect connectivity among vertices that have any incident edge. We can build a union-find (disjoint set) over the 26 letters, and for each word, if first != last, union(first, last). For loops (first == last), we don't union anything but we mark that vertex as present. Then after processing all words, we check that for all letters that have any degree (in+out >0), they belong to the same union-find set. But careful: If there is a vertex with only loops and no edges to others, it will be in its own set (since we never union it with anyone). If there are multiple such vertices, they will be separate sets, violating connectivity. So we need to ensure all vertices with degree >0 are in the same component. However, if there is a component that includes some vertices via unions, and there are other vertices that have only loops (self-edges) and no edges connecting to the main component, they are separate components. So we must check that the number of "active" vertices (with degree>0) that belong to the same set is exactly the total number of active vertices. To do this, we can find the set of vertices that have degree>0. Choose one representative among them, then ensure all active vertices are in the same union set as that representative (taking into account that loops don't union, so a vertex with only loops will have itself as its own set). So we need to union only when first != last. But also we could treat loops as connecting the vertex to itself, but that doesn't help connectivity. So we need to handle them separately.
Alternatively, we could do a BFS/DFS on the undirected graph built from edges where we treat each directed edge as an undirected connection. Loops are irrelevant for connectivity because they don't connect to other vertices. So we can build an adjacency list for undirected graph ignoring loops. Then start from some vertex with degree>0, do BFS, and mark visited. Then check that all vertices with degree>0 are visited.
Thus steps:
For each dataset:
- n = first integer.
- If n==0, break.
- Initialize arrays in[26], out[26] to 0.
- Initialize a boolean array has[26] = false (or degree >0).
- For each word:
- first = word[0] (char), last = word[-1] (last char)
- Convert to index 0-25.
- out[first]++, in[last]++.
- has[first]=true, has[last]=true.
- If first != last: add undirected edge between first and last (for connectivity). We can simply maintain a union-find or adjacency list.
- After processing all words:
- Check balance: for i in 0..25, if in[i] != out[i], then fail -> output "NG".
- Check connectivity:
- Count vertices with has[i] true. If count == 0? n>=2 so at least 2 words, there will be some vertices. But could be that all words are loops on same letter? Then that letter has degree>0, and other letters have degree 0. So only one vertex active. That is trivially connected. So if number of active vertices <= 1, connectivity condition is automatically satisfied (OK). Otherwise, we need to ensure all active vertices are in one connected component.
- Build graph: we can use union-find: Initialize parent[26]. For each word where first != last, union(first,last). After processing, find the root of any active vertex (first active vertex encountered). Then for all other active vertices, check if they have same root. If not, fail.
- Note: For loops (first==last), the vertex is active but not unioned with anyone. So if there are multiple active vertices that are only loops (each with only self-loops and no edges to others), they will have different roots, causing failure.
- If both conditions pass, output "OK", else "NG".
But wait: There's an edge case: What if there are active vertices that are only loops on the same letter? That's fine: only one active vertex. If there are multiple active vertices, they must be connected via edges where first != last. If there is a vertex with only loops, and there are other vertices connected among themselves, but the loop vertex is not connected to them, then it's disconnected -> fail.
Now confirm with examples.
Example Input:
5
apple
yellow
georgia
king
email
Let's compute first/last:
apple: a e? Actually apple: first 'a', last 'e'? apple ends with e? apple -> a, e? Actually "apple": a, last e? Wait "apple" ends with 'e'? Actually "apple" is a-p-p-l-e, so last e. So edge a->e.
yellow: y w? last w? Actually "yellow": y, w? ends with w? yellow -> y, w? yellow is y-e-l-l-o-w, so last w. So y->w.
georgia: g a? last a? "georgia": g, a? Actually georgia ends with a? georgia: g-e-o-r-g-i-a, so last a. So g->a.
king: k g? last g? "king": k, g? ends with g? king -> k, g. So k->g.
email: e l? "email": e, l? email ends with l? email is e-m-a-i-l, so last l. So e->l.
Now compute indegree/outdegree:
Vertices: a, e, y, w, g, k, l.
out: a->e => out[a]++, in[e]++.
y->w => out[y]++, in[w]++.
g->a => out[g]++, in[a]++.
k->g => out[k]++, in[g]++.
e->l => out[e]++, in[l]++.
So:
out[a]=1, in[a]=1 (from g)
out[e]=1, in[e]=1 (from a)
out[y]=1, in[y]=0? Actually y only out to w, no in.
out[w]=0, in[w]=1 (from y)
out[g]=1, in[g]=1 (from k)
out[k]=1, in[k]=0? Actually k only out to g, no in.
out[l]=0, in[l]=1 (from e)
Thus imbalances: y has out=1, in=0; w has out=0, in=1; k has out=1, in=0; l has out=0, in=1. So fails balance. So output "NG". That matches example.
Second dataset:
7
apple
yellow
georgia
king
email
wink
lucky
We already have 5 words above, plus:
wink: w k? first w, last k? Actually "wink": w i n k? ends with k? wink -> w, k? w i n k, last k. So w->k.
lucky: l y? "lucky": l, y? lucky ends with y? l-u-c-k-y, last y. So l->y.
Now compute additional:
out[w]++ (previously 0 becomes 1), in[k]++ (previously 0 becomes 1)
out[l]++ (previously 0 becomes 1), in[y]++ (previously 0 becomes 1)
Now totals:
out[a]=1, in[a]=1
out[e]=1, in[e]=1
out[y]=1, in[y]=1 (from lucky)
out[w]=1, in[w]=1 (from yellow)
out[g]=1, in[g]=1
out[k]=1, in[k]=1 (from wink)
out[l]=1, in[l]=1 (from email)
All balanced! Good.
Connectivity: edges: a-e, y-w, g-a, k-g, e-l, w-k, l-y. Let's list undirected connections:
a-e, y-w, g-a, k-g, e-l, w-k, l-y.
Vertices: a, e, y, w, g, k, l. Check connectivity: a connected to e and g. e to a and l. l to e and y. y to l and w. w to y and k. k to w and g. g to k and a. So it's all connected. So OK. Output "OK". That matches example.
Thus our reasoning is correct.
Now, note that the number of datasets ≤ 50, n ≤ 10000, so simple O(n) per dataset is fine.
Now, we need to pay attention to input: "n" words, each word up to 32 lowercase letters. The input ends with a line containing 0.
Implementation plan:
- While True:
- Read line for n. If n == 0: break.
- Initialize arrays: indeg = [0]*26, outdeg = [0]*26, present = [False]*26.
- Also union-find: parent = list(range(26)), rank/size optional.
- For i in range(n):
- word = input().strip()
- if word length maybe 0? but assumed non-empty.
- first = ord(word[0]) - ord('a')
- last = ord(word[-1]) - ord('a')
- outdeg[first] += 1
- indeg[last] += 1
- present[first] = True
- present[last] = True
- if first != last:
- After reading all words:
- Check balance: for i in range(26):
if indeg[i] != outdeg[i]:
print("NG")
break
else: (if no break)
- Check connectivity:
- Find list of active vertices: indices where present[i] is True.
- If len(active) == 0: (should not happen as n>=2, but just in case) print("OK")? Actually if n>=2, there must be some letters, but maybe all words are empty? Not possible.
- Else:
- Pick root = find(active[0])
- For each v in active[1:]:
if find(v) != root:
print("NG")
break
else:
print("OK")
- (If balance fails, we already printed NG and continue to next dataset.)
- Important: We must handle the case where there is only one active vertex (e.g., all words start and end with same letter). Then connectivity is trivially satisfied, because all active vertices are the same. But our union-find might not have united them because for loops we didn't union. However, if there is only one active vertex, our loop over active[1:] will be empty, so condition passes. So that's fine.
- Edge case: Multiple active vertices but some are only loops? For example: words: "aa" (a->a) and "bb" (b->b). Then present[a]=True, present[b]=True. indeg[a]=1 outdeg[a]=1; indeg[b]=1 outdeg[b]=1 -> balanced. union-find: no unions because first==last for both. So active vertices a and b are in different sets. Our check will detect that and output NG. That is correct, because we cannot form a single cycle using both words: Starting with "aa", ends with a; next word "bb" starts with b, which does not match a. And there is no way to order them because they are separate components. So NG.
Now, is there any scenario where the graph is weakly connected but not strongly connected due to directionality? As argued, weak connectivity + balance implies strong connectivity. So our condition is sufficient.
Thus solution is straightforward.
But careful: There is also the possibility that some vertices have total degree zero (not present). We ignore them.
Now, we should also consider that the graph might have isolated vertices with degree zero; we ignore.
Thus the solution is to check Eulerian circuit conditions.
But wait, there's another nuance: In Eulerian circuit for directed multigraphs, the condition is exactly: all vertices with nonzero degree belong to a single weakly connected component, and indegree == outdegree for every vertex. That is what we are using.
So we implement that.
Now, confirm with some tricky cases:
-
n=2, words: "ab", "ba". first/last: a->b, b->a. indeg: a:1 (from b), out: a:1; b:1, out:1. active vertices: a,b. They are connected via edge a<->b (undirected). So OK. Indeed can order: "ab" then "ba": ab ends with b, ba starts with b, and last of ba is a, first of ab is a => cycle.
-
n=2, words: "aa", "aa". Both loops on a. indeg[a]=2, outdeg[a]=2. active vertices only a. OK. Ordering: any order works? first "aa" ends with a, next "aa" starts with a, last ends with a, first starts with a => cycle. So OK.
-
n=2, words: "ab", "bc". a->b, b->c. indeg: a:0 out:1; b:1 in (from a), out:1 (to c); c:1 in, out:0. Not balanced, so NG. Indeed can't cycle because start a, end c.
-
n=3, words: "ab", "bc", "ca". a->b, b->c, c->a. Balanced, connected -> OK.
-
n=3, words: "ab", "bc", "cb". a->b, b->c, c->b. indeg: a:0 out1; b: in from a and c =2, out: to c =1? Actually b->c gives out 1; so b: out=1, in=2 imbalance. So NG.
Now consider case where graph is weakly connected but not balanced -> NG.
Now consider case where graph balanced but weakly disconnected -> NG.
Now, note: The problem says "use all the words to make a shiritori in order, and then the first letter of the first word and the last letter of the last word are the same." So they require a cycle. So yes.
Thus answer is to check Eulerian circuit.
Now, implement union-find.
Potential pitfalls:
-
Input reading: Use sys.stdin.read() to read all lines for efficiency, or just while loop with input(). There may be many datasets but total n per dataset up to 10000, and max datasets 50, so total words up to 500k, which is fine for Python's input().
-
Words may be empty? Not likely.
-
Be careful: When words have length 1? The problem says up to 32 single-byte lowercase letters; could be length 1. Then first and last are same character. That's a loop. That's okay.
-
Edge case: n might be 0? But problem says n≥2. The termination is a line with 0.
-
Output exactly "OK" or "NG" (uppercase).
Now, let's test with provided example.
Implementation details:
We'll define find and union functions.
Pseudo:
import sys
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(x,y):
rx, ry = find(x), find(y)
if rx != ry:
parent[ry] = rx # or union by rank
But we don't need rank; just simple union is fine because only 26 nodes.
Now:
def solve():
import sys
data = sys.stdin.read().splitlines()
it = iter(data)
out_lines = []
for line in it:
if not line:
continue # skip empty lines maybe
n = int(line.strip())
if n == 0:
break
indeg = [0]*26
outdeg = [0]*26
present = [False]*26
parent = list(range(26))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(x,y):
rx, ry = find(x), find(y)
if rx != ry:
parent[ry] = rx
for _ in range(n):
word = next(it).strip()
if not word:
# skip? but not expected
continue
first = ord(word[0]) - 97
last = ord(word[-1]) - 97
outdeg[first] += 1
indeg[last] += 1
present[first] = True
present[last] = True
if first != last:
union(first, last)
# Check balance
balanced = True
for i in range(26):
if indeg[i] != outdeg[i]:
balanced = False
break
if not balanced:
out_lines.append("NG")
continue
# Check connectivity
# Get list of vertices with present True
active = [i for i in range(26) if present[i]]
if len(active) == 0:
# no words? but n>=2 so improbable
out_lines.append("OK")
continue
# Find root of first active
root = find(active[0])
connected = True
for v in active[1:]:
if find(v) != root:
connected = False
break
if connected:
out_lines.append("OK")
else:
out_lines.append("NG")
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()
Now, one more nuance: In union-find, we union only when first!=last. But what about loops? They don't connect. However, if there is a vertex with only loops and no other edges, it will be its own component. But as argued, that's correct.
But consider scenario: graph has two vertices, each with loops, and also an edge between them? That would be unioned. So fine.
Now, consider scenario: All words are loops on the same vertex, but also there is an edge from that vertex to itself? Actually loops already. So active vertices = {a}. Balanced and connectivity trivially satisfied -> OK.
Now, consider scenario: All words are loops, but on multiple vertices, e.g., "aa", "bb". Balanced? indeg[a]=1, outdeg[a]=1; indeg[b]=1, outdeg[b]=1. But active vertices a and b are not connected (since no union). So connectivity fails -> NG. Correct.
Thus solution is good.
But wait: Is there any special case where the graph is weakly connected but not strongly connected but still has Eulerian circuit? Let's double-check with theory: A directed graph has an Eulerian circuit iff each vertex has indegree=outdegree and the graph is "weakly connected" and "all vertices with nonzero degree belong to a single strongly connected component". However, as argued, weak connectivity and balance imply strong connectivity for vertices with nonzero degree, because otherwise there would be a source or sink SCC. Let's formally prove: Suppose the directed graph G (with all vertices having indegree=outdegree) is weakly connected but not strongly connected. Then the condensation graph (DAG) has at least two SCCs. Since it's a DAG, there exists a source SCC S (no incoming edges from other SCCs). For S, edges from other SCCs to S are 0. Since each vertex in S has indegree=outdegree, the sum of outdegrees of S equals sum of indegrees of S. The sum of indegrees of S includes internal edges (within S) plus edges from other SCCs to S (