codeforces Good Bye 2013 379D New Year Letter

题目链接:http://codeforces.com/problemset/problem/379/D

【题目大意】

      告诉你初始字符串S1、S2的长度和递推次数k, 使用类似斐波纳契数列的字符串合并的递推操作,使得最后得到的字符串中刚好含有x个"AC",现在要你构造出满足条件的S1和S2。

【分析】

      最终结果中有些"AC"可能是应为在合并时一个字符串的尾部和另一个字符串的首部合并而成,这就跟原始字符串的首尾字符有关,不同的情况在K次递推后多产生的"AC"数是不同的,所以这里既要枚举下初始串的首尾字符,计算出因合并产生的"AC"数sum有多少。

      现在可以忽略合并产生的"AC"了,假设S1中有a个"AC",S2中有b个"AC",则经过k次递推由这些"AC"组合成的"AC"数量为:fib[k-2]*a+fib[k-1]*b。

      所以最终的结果为:

         f[k]=fib[k-2]*a+fib[k-1]*b+sum;

     f[k]=x 已知,sum可以枚举获得 ,于是只需枚举a 即可知道 a和b 的值,对于一组 a,b值看能否构造出符合条件的字符串就好了。

     其实可以不用枚举a,用不定方程来解就好了,当a,b很大时速度更快。

【代码】

 

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <algorithm>
 4 #include <iostream>
 5 using namespace std;
 6 long long fib[100];
 7 int k,x,n,m,aa,bb;
 8 char ansa[103],ansb[103];
 9 int calc(int s1,int s2)
10 {
11     int a=s1,b=s2,t;
12     int ca=0,cb=0,sum=0;
13     for (int i=3;i<=k;++i)
14     {
15         sum=ca+cb;
16         if ((a&2)&&!(a&1)&&(b&8)&&(b&4)) ++sum;
17         t=b,b=(a&(3<<2))|(b&3);
18         a=t,t=cb,cb=sum,ca=t;
19     }
20     return sum;
21 }
22 bool product(int t,int code,char *p,int len)
23 {
24     int pp=1;
25     if (len==1 && ((code>>2)&3)!=(code &3)) return false;
26     if (len==2 && code==11) --t;
27     if ((code>>2)==3) p[0]='C'; else
28     if ((code>>2)==2) p[0]='A'; else p[0]='B';
29     if ((code>>2)==2 && t && len>2) --t,p[pp++]='C';
30     while (pp<len-2 && t) p[pp++]='A',p[pp++]='C',--t;
31     p[len]='\0';
32     if ((code&3)==3) p[len-1]='C'; else
33     if ((code&3)==2) p[len-1]='A'; else p[len-1]='B';
34     if (pp<=len-2 && p[len-1]=='C' && t) --t,p[len-2]='A',--len;
35     while (pp<len-1) p[pp++]='B';
36     if (t) return false;
37     return true;
38 }
39 bool calc2(int ret)
40 {
41     int p=x-ret;
42     for (int a=0;a<=50;++a)
43     {
44         int pp=p-a*fib[k-2];
45         if (pp%fib[k-1]!=0) continue;
46        if (product(a,aa,ansa,n) && product(pp/fib[k-1],bb,ansb,m))
47          return true;
48     }
49     return false;
50 }
51 int main()
52 {
53     fib[0]=0;fib[1]=fib[2]=1;
54     for (int i=3;i<=50;++i) fib[i]=fib[i-1]+fib[i-2];
55     while (~scanf("%d%d%d%d",&k,&x,&n,&m))
56     {
57         bool fla=true;
58          for (aa=0;aa<16 && fla;++aa)
59             for (bb=0;bb<16;++bb)
60          {
61              if (calc2(calc(aa,bb)))
62                  {printf("%s\n%s\n",ansa,ansb),fla=false;break;}
63          }
64         if (fla) puts("Happy new year!");
65     }
66 }
View Code

 

 

【PS】

     基本上半年没写博客了,2014的第一篇~

    元旦快乐!!

posted @ 2014-01-01 10:40  wuminye  阅读(321)  评论(0编辑  收藏  举报