問題描述:
從三個元素的集合[A,B,C]中選取元素生成一個N 個字符組成的序列,使得沒有兩個相鄰的子序列(子序列長度=2)相同,例:N=5 時ABCBA 是合格的,而序列ABCBC 與ABABC 是不合格的,因為其中子序列BC,AB 是相同的。
輸入N(1<=N<=12),求出滿足條件的N 個字符的所有序列和其總數。
輸入樣例:
4
輸出樣例:
72
這道題剛開始我想的是dp,而且寫出來后當 n == 4 的時候也確實是72,結果交上去就GG了。每一個測試點數都大了一些。調試了半天還是沒調出來。
所以這里就先講一下正解吧。因為數據范圍才是1到12,所以比較暴力的算法就能過,暴力的算法就是搜索了,作為一個oier,應該有這種數據的敏感性。
對於每一位的字符,搜索的范圍就是A到C,然后只要判斷 i == a[x - 2] && a[x - 1] == a[x - 3] 的時候舍去就行了,其他情況正常遞歸。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<cmath> 5 #include<iostream> 6 #include<string> 7 using namespace std; 8 typedef long long ll; 9 const int maxn = 1e4 + 5; 10 int n, ans, a[maxn]; 11 void dfs(int x) 12 { 13 if(x == n + 1) {ans++; return;} 14 for(int i = 1; i <= 3; ++i) 15 { 16 if(i == a[x - 2] && a[x - 1] == a[x - 3]) continue; 17 a[x] = i; 18 dfs(x+1); 19 } 20 } 21 22 int main() 23 { 24 freopen("characts.in","r",stdin); 25 freopen("characts.out","w",stdout); 26 scanf("%d", &n); 27 dfs(1); 28 printf("%d\n", ans); 29 return 0; 30 }