poj 1699 Best Sequence (搜尋技巧 剪枝 dfs)

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   

題目連結

題意:給出幾個基因片段,要求你將它們排列成一個最短的序列,序列中使用了所有的基因片段,而且不能翻轉基因。

分析:先計算出add數組,再dfs枚舉。

 1 #include <iostream> 2 #include <cstring> 3 #include <cstdlib> 4 #include <cmath> 5 #include <cstdio> 6 #include <vector> 7 #include <algorithm> 8 #define LL long long 9 using namespace std;10 const int maxn = 20+10;11 const int INF = 1<<28;12 int n, len[maxn], add[maxn][maxn], ans;13 bool vis[maxn];14 char s[maxn][maxn];15 16 void cal(int a, int b, int lena, int lenb) //add計算串a在串b,前面增加的字元個數。17 {18     int i, j, k, f, x;19     for(i = 0; i < lena; i++)20     {21         f = 0;22         for(j = 0, k = i; j < lenb && k < lena; j++, k++)23         {24             if(s[a][k] == s[b][j]) continue;25             else { f = 1; break; }26         }27         if(f == 0) break;28     }29     x = lena - i;30     add[a][b] = lenb - x;31     if(add[a][b]<0) add[a][b] = 0;32 }33 void dfs(int pre, int sum, int lenth) //分別代表之前的串,和串的總數,總串的長度。34 {35     if(lenth >= ans) return;36     if(sum == n)37     {38         if(lenth < ans) ans = lenth;39         return;40     }41     for(int i = 0; i < n; i++)42     {43       if(!vis[i])44       {45           vis[i] = true;46           if(add[pre][i]==0) //一定要注意這是存在包含串,如abcdabc 包含 dab47           //串a包含串b,等價於從a到b的邊等於0,那麼這時,狀態在轉移時,在原本48           //是以串a結尾的狀態加入串b,此時目標狀態仍然是以串a結尾,這裡需要注意。49           dfs(pre, sum+1, lenth+add[pre][i]);50           else51           dfs(i, sum+1, lenth+add[pre][i]);52           vis[i] = false;53       }54     }55 }56 int main()57 {58     int t, i, j;59     scanf("%d", &t);60     while(t--)61     {62         ans = INF;63         memset(add, 0, sizeof(add));64         memset(vis, false, sizeof(vis));65         scanf("%d", &n);66         for(i = 0; i < n; i++)67         {68             scanf("%s", s[i]);69             len[i] = strlen(s[i]);70         }71         for(i = 0; i < n; i++)72         for(j = 0; j < n; j++)73         cal(i, j, len[i], len[j]);74         for(i = 0; i < n; i++)75         {76             vis[i] = true;77             dfs(i, 1, len[i]);78             vis[i] = false;79         }80         printf("%d\n", ans);81     }82     return 0;83 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.