困難的串——回溯法

來源:互聯網
上載者:User

標籤:超過   class   mes   scan   stream   iostream   strong   字串   包含   

題目

如果一個字串包含兩個相鄰的重複字串,則稱它是“容易的串”,其他串稱為“困難的串”。輸入正整數n和L,輸出由前L個字元組成的、字典序第n的困難的串。例如,當L = 3時,前7個困難的串分別是A、AB、ABA、ABAC、ABACA、ABACAB、ABACABA。輸入保證答案不超過80個字元。

解題思路

從左至右依次考慮每個位置上的字元。因此,關鍵在於如何判斷當前字串是否已經存在連續的重複字串。類似於八皇后,我們只需判斷當前皇后和前面的皇后是否衝突,而不必判斷以前的皇后之間是否衝突(因為以前的已經判斷過了)。同樣的道理,我們只需判斷當前串的尾碼,而非所有的字串。

代碼實現

 1 #include<stdio.h> 2 #include<iostream> 3 #include<algorithm> 4 using namespace std; 5  6 const int maxn = 80 + 10; 7 int n, L; 8 int cnt; 9 int S[maxn];10 11 bool dfs(int cur)12 {13     if (cnt++ == n)14     {15         for (int i = 0; i < cur; i++)16         {17             if (i % 64 == 0 && i)  printf("\n");18             else if (i % 4 == 0 && i)  printf(" ");    19             printf("%c", ‘A‘ + S[i]);20         }21         printf("\n%d\n",cur);22         return 1;23     }24     for (int i = 0; i < L; i++)25     {26         S[cur] = i;27         int ok = 1;28         for (int j = 1; j * 2 <= cur + 1; j++)    //嘗試長度為j * 2的尾碼29         {30             int equal = 1;31             for (int k = 0; k < j; k++)            //檢查後一半是否等於前一半32             {33                 if (S[cur - k] != S[cur - j - k])34                 {35                     equal = 0;36                     break;37                 }38             }39             if (equal)40             {41                 ok = 0;42                 break;43             }44         }45         if (ok)  if (dfs(cur + 1))  return 1;46     }47     return 0;48 }49 50 int main()51 {52     while (scanf("%d%d",&n,&L) == 2 && n)53     {54         cnt = 0;55         dfs(0);56     }57     return 0;58 }

 

困難的串——回溯法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.