多字符串重構

問題描述:
第一行輸入n和m,代表n個字符串,每個字符串長度爲m;接下來n行爲長度爲m的n個字符串,n個字符串構成集合A。
從任意字符串中選取第一個字符爲重構字符串第一個字符,從任意字符串中選取第二個字符爲重構字符串第二個字符,以此類推,求出以集合A重構出來的字符串集合S。

分析思路:
如用暴力求解,時間複雜度爲O(n^m),易運行超時,而且循環層數是變量,不好構建循環體;考慮遞歸回溯法(揹包0-1問題)求取,前一過程已經取得的結果繼續保留與棧(實際代碼存於vector)中。

代碼:

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<sstream>
using namespace std;

vector<string> all_str;
vector<char> build_str;

void cal(vector<string> &a,int index,int m)
{
    if(index==m)
    {
        string temp;
        for(int i=0;i<m;i++)
        {
            temp=temp+build_str[i];
        }
        auto p=find(all_str.begin(),all_str.end(),temp);
        if(p==all_str.end())
            all_str.push_back(temp);
        return ;
    }
    if(index<m)
    {
        for(int i=0;i<a.size();i++)
        {
            build_str.push_back(a[i][index]);
            cal(a,index+1,m);
            build_str.pop_back();
        }
    }
}

int main()
{
    int n,m;
    istringstream is;
    string s;
    getline(cin,s);
    is.clear();
    is.str(s);
    is>>n>>m;
    vector<string> a;
    for(int i=0;i<m;i++)
    {
        string temp;
        is.clear();
        getline(cin,s);
        is.str(s);
        is>>temp;
        a.push_back(temp);
    }
    all_str=a;
    cal(a,0,m);
    //sort(all.begin(),all.end());
    cout<<"The total size of the rebuild string is: "<<all_str.size()<<endl;
    cout<<"print the total element: "<<endl;
    for(auto i:all_str)
       cout << i << endl;
    return 0;
}

輸入:

3 3
ABC
DEF
GHI

輸出:

The total size of the rebuild string is: 27
print the total element:
ABC
DEF
GHI
ABF
ABI
AEC
AEF
AEI
AHC
AHF
AHI
DBC
DBF
DBI
DEC
DEI
DHC
DHF
DHI
GBC
GBF
GBI
GEC
GEF
GEI
GHC
GHF

Process returned 0 (0x0)   execution time : 9.127 s
Press any key to continue.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章