sicily 1198 substring 组合问题
1198. Substring
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
Dr lee cuts a string S into N pieces,s[1],…,s[N].
Now, Dr lee gives you these N sub-strings: s[1],…s[N]. There might be several possibilities that the string S could be. For example, if Dr. lee gives you three sub-strings {“a”,“ab”,”ac”}, the string S could be “aabac”,”aacab”,”abaac”,…
Your task is to output the lexicographically smallest S.
Input
The first line of the input is a positive integer T. T is the number of the test cases followed.
The first line of each test case is a positive integer N (1 <=N<= 8 ) which represents the number of sub-strings. After that, N lines followed. The i-th line is the i-th sub-string s[i]. Assume that the length of each sub-string is positive and less than 100.
Output
The output of each test is the lexicographically smallest S. No redundant spaces are needed.
Sample Input
1 3 a ab ac
Sample Output
aabac
Problem Source
ZSUACM Team Member
此题由于规模不大,所以可以直接用枚举出所有可能组合,然后选择按字典序最小的字符串输出,用到递归实现了一个字符数组的全排列,每次均进行拼接保存到一个vector中用于返回,vector记得使用引用
#include <iostream> #include <vector> #include <string> using namespace std; void swap(string &a, string &b); void perminent(vector<string> &result, string substrs[], int subnum, int index); int main() { int t; cin >> t; while (t-- > 0) { int subnum; string substr; vector<string> result; cin >> subnum; string substrs[subnum]; for (int i = 0; i < subnum; i++) { cin >> substr; substrs[i] = substr; } perminent(result, substrs, subnum, 0); string minstr = result[0]; //好该死呀!!!这里把result.size(),写成了subnum!!! 这样搞了一个多小时 for (int i = 1; i < result.size(); i++) { if (minstr.compare(0, minstr.size(), result[i]) > 0) { minstr = result[i]; } } cout << minstr << endl; } return 0; } void swap(string &a, string &b) { string temp = a; a = b; b = temp; } //获得该字符串数组的一个全排列 void perminent(vector<string> &result, string substrs[], int subnum, int index) { if (index == subnum-1) { string temp; for (int i = 0; i < subnum; i++) { temp += substrs[i]; } result.push_back(temp);//result为引用调用 } else { for (int i = index; i < subnum; i++) { //获得该数组的全排列的关键 swap(substrs[i], substrs[index]); //把数组当前元素放在数组开头 perminent(result, substrs, subnum, index+1); swap(substrs[i], substrs[index]);//还原回原来数组,继续递归,等下把数组下一个元素放在开头 } } }