poj 1699 Best Sequence (搜索技巧 剪枝 dfs)
生活随笔
收集整理的這篇文章主要介紹了
poj 1699 Best Sequence (搜索技巧 剪枝 dfs)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目鏈接
題意:給出幾個(gè)基因片段,要求你將它們排列成一個(gè)最短的序列,序列中使用了所有的基因片段,而且不能翻轉(zhuǎn)基因。
分析:先計(jì)算出add數(shù)組,再dfs枚舉。
空間復(fù)雜度O(n*n), ?最壞時(shí)間復(fù)雜度 O(n^n),但是剪枝以后很快,因?yàn)楹枚嗨巡坏胶竺?#xff0c;搜不到第n層。
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計(jì)算串a(chǎn)在串b,前面增加的字符個(gè)數(shù)。 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) //分別代表之前的串,和串的總數(shù),總串的長度。 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 包含 dab 47 //串a(chǎn)包含串b,等價(jià)于從a到b的邊等于0,那么這時(shí),狀態(tài)在轉(zhuǎn)移時(shí),在原本 48 //是以串a(chǎn)結(jié)尾的狀態(tài)加入串b,此時(shí)目標(biāo)狀態(tài)仍然是以串a(chǎn)結(jié)尾,這里需要注意。 49 dfs(pre, sum+1, lenth+add[pre][i]); 50 else 51 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 }轉(zhuǎn)載于:https://www.cnblogs.com/bfshm/p/3863925.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的poj 1699 Best Sequence (搜索技巧 剪枝 dfs)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .Net 4.0 (2)
- 下一篇: NAPTR和SRV记录