1. 程式人生 > 實用技巧 >Codeforces Round #658 (Div. 2) C1. Prefix Flip (Easy Version) (構造)

Codeforces Round #658 (Div. 2) C1. Prefix Flip (Easy Version) (構造)

  • 題意:給你兩個長度為\(n\)的01串\(s\)\(t\),可以選擇\(s\)的前幾位,取反然後反轉,保證\(s\)總能通過不超過\(3n\)的操作得到\(t\),輸出變換總數,和每次變換的位置.

  • 題解:構造題一定要充分利用題目所給的條件,對於\(s\)中的某一位i,假如它和\(t\)中的對應位置不同,我們先對前i個字元取反反轉,然後再對第一個字元取反反轉(就選了一個,反不反都無所謂),在取前i個位置取反反轉,這樣,我們就將第i個位置變換了,消耗了3次操作.這樣就一定能保證在\(3n\)之內完成操作.

  • 程式碼:

    int t;
    int n;
    string s,tmp;
    vector<int> ans;
     
    int main() {
        ios::sync_with_stdio(false);cin.tie(0);
        cin>>t;
         while(t--){
             cin>>n;
             cin>>s>>tmp;
             ans.clear();
             for(int i=0;i<s.size();++i){
                 if(s[i]!=tmp[i]){
                     ans.pb(i+1);
                     ans.pb(1);
                     ans.pb(i+1);
                 }
             }
             cout<<ans.size()<<" ";
             for(auto w:ans){
                 cout<<w<<" ";
             }
             cout<<endl;
         }
     
        return 0;
    }