Time limit: 1 second
Memory limit: 256 MB
Amin wants to participate in an exam
n
He must remember n different words, these words are all in length
k
k are Amin, who is a lazy person, instead of memorizing these words, decides to write them down and cheat.
Amin has his own style for cheating. he wants
n
Write n characters around a circle so that all
n
The n words that had to be memorized can be found by starting from one of these
n
n character and move clockwise and note down
k
k characters back to back.
Note that the order in which the words appear around the circle does not matter and they can appear in any order, but this
n
n words are not necessarily distinct and if a word
m
m times appear in the input, it must also be exactly around the circle
m
be seen m times.
Help Amin to get this arrangement of characters. If there are several arrangements, print one of them as desired. Also, if this is not possible, indicate this bad news by printing -1.
input
In the first line you enter two integers
n
n and
k
k is given. in
n
The next n lines are each a string long
k
k is given. All these strings are composed of English lowercase letters.
1
≤
n
x
k
≤
500
,
000
1≤n×k≤500,000
output
In a single output line a string long
n
Print n, which is the answer to the problem. String order is clockwise from left to right. If there is no answer to the problem, print -1 on the only output line.
Example
Sample entry 1
3 3
abc
bca
cab
Plain text
Sample output 1
abc
Plain text
Sample entry 2
4 2
aa
ab
ba
bb
Plain text
Sample output 2
aabb write in c++
Assistant
To solve this problem, we need to determine if it's possible to arrange the provided words around a circle in such a way that every word can be read by starting at some position and moving clockwise.
Step-by-Step Reasoning:
Graph Representation:
Each word of length k can be split into a prefix (first k-1 characters) and a suffix (last k-1 characters).
These prefixes and suffixes represent nodes in a directed graph.
Each word corresponds to an edge from its prefix to its suffix.
Eulerian Circuit:
To ensure that all words can be arranged in a circle, the graph must have an Eulerian circuit. This means:
Each node should have the same in-degree as out-degree.
All nodes with edges must be part of a single connected component.
If these conditions are satisfied, we can use Hierholzer's algorithm to find an Eulerian circuit.
Reconstruction of the Circular String:
Once the Eulerian circuit is found, we reconstruct the circular string by concatenating the characters derived from the circuit.
The resulting string should have exactly n characters, matching the requirement.
Edge Cases:
When k=1, every word is simply one character.
We need to handle scenarios where it’s not possible to form such a circular string by checking if the Eulerian conditions are met.
Implementation:
Here's the C++ code that implements the above logic:
cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<string> words(n);
for(auto &s: words) cin >> s;
vector<string> nodes;
if(k >1){
for(auto &s: words){
string prefix = s.substr(0, k-1);
string suffix = s.substr(1, k-1);
nodes.push_back(prefix);
nodes.push_back(suffix);
}
}
else{
// For k ==1, all prefixes and suffixes are empty strings
nodes.push_back("");
}
// Remove duplicates
sort(nodes.begin(), nodes.end());
nodes.erase(unique(nodes.begin(), nodes.end()), nodes.end());
// Function to get ID of a string
auto get_id = [&](const string &s) -> int{
return lower_bound(nodes.begin(), nodes.end(), s) - nodes.begin();
};
// Build adjacency list
int m = nodes.size();
vector<vector<int>> adj(m);
if(k >1){
for(auto &s: words){
string prefix = s.substr(0, k-1);
string suffix = s.substr(1, k-1);
int u = get_id(prefix);
int v = get_id(suffix);
adj[u].push_back(v);
}
}
else{
// For k ==1, all edges go from node 0 to node 0
// Each word is a single character, which is the edge label
// To handle it, we need to map each character to an edge
// But since node is empty string, and we need to collect characters
// Modify the approach to store characters separately
// Instead, since k==1, the circular string is just the list of characters
// So we can just collect all characters and output them in any order
// But to fit the Eulerian circuit approach, we can treat each character as an edge label
// and all edges go from node 0 to node 0 with labels as characters
// To reconstruct, collect the characters in the order of the circuit
// Implement accordingly
// Modify nodes to store the empty string only
// Assign node 0 to empty string
// Each edge corresponds to a character
// We need to store the characters in the adjacency list
// So instead of having adj[u] as list of v, have adj[u] as list of characters
// Implement separately
// For simplicity, handle k==1 separately
// Collect all characters
// Check if all characters can form a circular string
// Which is always possible by arranging the characters in any order
// So just collect the characters and output them
// However, if all characters must appear exactly as given
// So output the characters in the given order
// But the problem allows any order, so we can sort them or any permutation
// To fit the standard approach, just output the first n characters
// Implement as follows:
// Collect all characters
string s_all;
for(auto &s: words) s_all += s;
// Output any permutation, here just the order given
// Since it's circular, any order is fine
// To fit with standard, just output the characters in the order they appear
// which corresponds to the circuit
// But to ensure it wraps around, just output the first n characters
// which are already n characters
// So output s_all
// But s_all has n characters
// Thus, output s_all
// Implement this
string s_all_output;
for(auto &s: words) s_all_output += s;
// Now, s_all_output is the circular string
// It must satisfy that each character appears exactly as many times as in words
// Which it does
// So output any permutation, here the given order
// Alternatively, you can arrange them in any order, but it's not required
// So just output s_all_output
cout << s_all_output;
return 0;
}
// Now, check in-degree == out-degree
vector<int> in_deg(m, 0), out_deg(m, 0);
for(int u=0; u<m; u++) out_deg[u] += adj[u].size();
for(int u=0; u<m; u++) {
for(auto &v: adj[u]) in_deg[v]++;
}
bool ok = true;
for(int u=0; u<m && ok; u++) {
if(in_deg[u] != out_deg[u]) {ok=false;}
}
if(!ok){
cout << "-1";
return 0;
}
// Find starting node
int start = 0;
for(int u=0; u<m; u++) {
if(adj[u].size() >0){
start = u;
break;
}
}
// Hierholzer's algorithm
vector<int> circuit;
vector<int> stack_path;
stack_path.push_back(start);
// To make it efficient, use indices
vector<int> ptr(m, 0);
while(!stack_path.empty()){
int u = stack_path.back();
if(ptr[u] < adj[u].size()){
int v = adj[u][ptr[u]];
ptr[u]++;
stack_path.push_back(v);
}
else{
circuit.push_back(u);
stack_path.pop_back();
}
}
// The circuit is in reverse order
reverse(circuit.begin(), circuit.end());
// Check if all edges are used
if(circuit.size() != n +1){
cout << "-1";
return 0;
}
// Reconstruct the string
string reconstructed = nodes[circuit[0]];
for(int i=1; i<circuit.size(); i++){
reconstructed += nodes[circuit[i]].back();
}
// Take the first n characters
if(reconstructed.size() < (size_t)n){
// This should not happen
cout << "-1";
return 0;
}
string circular_string = reconstructed.substr(0, n);
// Verify that circular_string has exactly n characters
// Output the result
cout << circular_string;
}
Explanation of the Code:
Reading Input:
We read the number of words n and the length k of each word.
We store all words in a vector.
Mapping Prefixes and Suffixes:
For each word, we extract the prefix and suffix.
These are stored in a list called nodes.
We remove duplicates and sort them to assign unique IDs using binary search.
Building the Graph:
We construct an adjacency list where each edge represents a transition from a prefix to a suffix.
We also calculate the in-degree and out-degree of each node to ensure they are equal.
Hierholzer's Algorithm:
If the in-degree and out-degree conditions are satisfied, we perform Hierholzer's algorithm to find an Eulerian circuit.
If an Eulerian circuit covering all edges exists, we proceed to reconstruct the string.
Reconstructing the Circular String:
We build the string based on the Eulerian circuit by taking the initial prefix and appending the last characters of each node in the circuit.
The first n characters of this reconstructed string represent the desired circular arrangement.
Handling Special Case for k=1:
When k=1, each word is a single character, and the solution involves simply arranging these characters in any order that maintains their multiplicity.
Output:
If a valid circular arrangement exists, it is printed. Otherwise, -1 is outputted indicating that no such arrangement is possible.
Conclusion:
This approach effectively transforms the problem into finding an Eulerian circuit in a directed graph, ensuring that the given words can be arranged in a circular manner as required.