两种写法。
题目分析:
观察题目所给图像进行思考,我们可以维护三个分数,, 表示现在在哪里, 表示在 左边离 最近的分数, 表示在 右边离 最近的分数,初始化 。
枚举读入的每一个字符,如果是 , 不变, 变成原来的 , 变成 ; 同理, 不变, 变成原来的 , 变成 。最后 就是答案。
时间复杂度:。
Code.
#include<bits/stdc++.h>
#define int long long
using namespace std;
struct node {int x,y;}; char s[1010]; int t,x,y;
signed main()
{
scanf("%lld",&t);
while(t --)
{
scanf("%s",s+1); node l={0,1},r={1,0},pl={1,1};
for(int i=1;i<=(int)strlen(s+1);i++)
if(s[i] == 'L') {r=pl; pl={l.x+pl.x,l.y+pl.y};}
else {l=pl; pl={pl.x+r.x,pl.y+r.y};}
printf("%lld/%lld\n",pl.x,pl.y);
}
return 0;
}
本人坐考场上想的奇怪东西。
我们可以将 的转移量分别用矩阵表示, 为当前字符串, 就是当前字符串的矩阵表示出来的分数。
那么针对任意一个 字符串,我们都可以将它变成若干个矩阵相乘的形式,以题目第二个样例为例:
所以答案就是:
推广到一般形式:
然后我们发现搞成这样并没有什么实质性的优化,直接乘是 的,它甚至还慢了,所以我们考虑一点矩阵上的优化。
显然,我们面对连续乘一堆 或 的时候,我们并不需要都乘,把它变成乘方的形式,举例:
然后就可以上矩阵快速幂了。
时间复杂度:,自带一个 的常数,按理说 越长效果越明显,这里只是不怎么明显罢了。
Code.
#include<bits/stdc++.h>
#define int long long
using namespace std; char ch[110],top;
struct node {int a[3][3]; node() {memset(a,0,sizeof a);}} L,R;
node operator *(const node &a,const node &b)
{
node res;
for(int k=1;k<=2;k++)
for(int i=1;i<=2;i++)
for(int j=1;j<=2;j++)
res.a[i][j]+=a.a[i][k]*b.a[k][j];
return res;
}
node ksm(node a,int b)
{
node res; for(int i=1;i<=2;i++) res.a[i][i]=1;
while(b) {if(b&1ll) res=(res*a); a=(a*a); b>>=1ll;}
return res;
}
signed main()
{
L.a[1][1]=1; L.a[1][2]=1; L.a[2][1]=0; L.a[2][2]=1;
R.a[1][1]=1; R.a[1][2]=0; R.a[2][1]=1; R.a[2][2]=1;
int t; scanf("%lld",&t);
while(t -- )
{
node res; for(int i=1;i<=2;i++) res.a[i][i]=1;
scanf("%s",ch+1);
for(int i=1,l=1;i<=(int)strlen(ch+1);i++)
{
if(i == 1) top=ch[1];
else if(top != ch[i] || i == (int)strlen(ch+1))
{
if(top == 'L') res=(res*ksm(L,i-1-l+1)),top='R',l=i;
else if(top == 'R') res=(res*ksm(R,i-1-l+1)),top='L',l=i;
}
}
if(ch[strlen(ch+1)] == 'L') res=(res*L); else res=(res*R);
int jk=res.a[2][1]+res.a[2][2],dk=res.a[1][1]+res.a[1][2],cd=__gcd(jk,dk);
printf("%lld/%lld\n",jk/cd,dk/cd);
}
return 0;
}研究了一个并没有什么用的东西导致后面挂分了。
