A. k-Stringtime limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
A string is called a k-string if it can be represented as k concatenated
copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string,
or a 6-string and so on. Obviously any string is a 1-string.
You are given a string s, consisting of lowercase English letters and a positive integer k.
Your task is to reorder the letters in the string sin such a way that the resulting string is a k-string.
Input
The first input line contains integer k (1 ≤ k ≤ 1000).
The second line contains s, all characters in s are
lowercase English letters. The string length s satisfies the inequality 1 ≤ |s| ≤ 1000,
where |s| is the length of string s.
Output
Rearrange the letters in string s in such a way that the result is a k-string.
Print the result on a single output line. If there are multiple solutions, print any of them.
If the solution doesn't exist, print "-1" (without quotes).
Sample test(s)input
2aazz
output
azaz
input
3abcabcabz
output
-1
ps:感謝莫莫的解題報告
這個題目主要是需要理解題意,靜下心來看下,其實很簡單。
題意:
題目給一個K,給定一個字串,裡麵包含若干字母。如果字串可以用裡面所有的字母重新組合為K-string,輸出重組以後的字串,否則輸出-1。K-string即為一個字串可以分為一個子串複製K倍然後得到字串。
解題思路:
先判斷是不是K-string,用一個數組儲存從a~z出現的次數。如果某一個次數不是K的倍數,那麼便直接輸出-1即可。否則則將裡面的次數全部除以K,用來輸出。
#include<iostream>#include<cstdio>#include<cmath>#include<cstring>#include<string>#include<algorithm>#include<map>using namespace std;char a[1004],c[1004]; //a是輸入的字串,c則是需要連續輸出K倍的子串int b[26]; //儲存a~z字母出現額次數int main(){ int i,j,k; while(cin>>k) { memset(b,0,sizeof(b)); cin>>a; for(i=0;i<strlen(a);i++) b[a[i]-'a']++; int flag=0; for(i=0;i<26;i++) if(b[i]%k!=0) //不滿足次數是K的倍數,跳出,輸出-1 { flag=1; break; } if(flag) cout<<"-1"<<endl; else { int ll=-1; for(i=0;i<26;i++) if(b[i]) { int x=b[i]/k; //次數除以K for(j=0;j<x;j++) c[++ll]=i+'a'; //用c來儲存需要輸出的子串 } c[++ll]='\0'; for(i=0;i<k;i++) //輸出重組以後的K-string cout<<c; cout<<endl; } } return 0;}