UVALive - 6577 Binary Tree 递推+找规律
题目链接:
http://acm.hust.edu.cn/vjudge/problem/48421
Binary Tree
输入
First line of the test file contains an integer N (≤ 20) denoting number of test cases. Hence follow N
test cases. Each test case consists of two non empty strings. First line will contain instruction string S
and the second line will contain the instruction string T. You may assume that there will not be any
letter other than L, R or U in these strings. Length of the strings will not be greater than 100000.
输出
For each test case print the case number followed by the number of nodes we can end up finally. Since
the answer may be large, you have to give the answer modulo 21092013.
样例
sample input
2
L
LU
L
Lsample output
Case 1: 3
Case 2: 2
题解
首先我们考虑只有LR,没有U的情况:
我们定义三个计数变量:ans=1,l=1,r=1;
其中ans为答案,l表示当前局势下,往左走一步能够访问到的新节点;r表示当前局势往右走一步能够访问到的新节点。
如果现在的输入是'L',那么显然会有ans+=l。并且不会影响r,且这些新节点还会创造出更多的能够往右走的新节点:r+=l。
那么,现在我们考虑有'U'的情况:
如果U没有上升到一个没有走过的点,显然是要亏一波的,还不如直接跳过。
因此我们只需要考虑往上走能够走到新节点的情况(用S串来获取信息):
如果父亲在左边(它是右儿子),那么将会有l+=1; ans+=1;
如果父亲在右边:那么有r+=1,ans+=1;
代码
#include<map>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#define X first
#define Y second
#define mkp make_pair
#define lson (o<<1)
#define rson ((o<<1)|1)
#define mid (l+(r-l)/2)
#define pb(v) push_back(v)
#define sz() size()
#define all(o) (o).begin(),(o).end()
#define clr(a,v) memset(a,v,sizeof(a))
#define bug(a) cout<<#a<<" = "<<a<<endl
#define rep(i,a,b) for(int i=a;i<(b);i++)
using namespace std;
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
typedef vector<pair<int,int> > VPII;
const int INF=0x3f3f3f3f;
const LL INFL=0x3f3f3f3f3f3f3f3fLL;
const double eps=1e-8;
const int maxn = 1e5+10;
const int mod=21092013;
char s1[maxn],s2[maxn];
vector<char> sta;
void add_mod(int &x,int y){ x=(x+y)%mod; }
void init(){
sta.clear();
}
int main() {
int tc,kase=0;
scanf("%d",&tc);
while(tc--){
init();
scanf("%s",s1);
int l1=strlen(s1);
rep(i,0,l1){
if(s1[i]=='U'){
if(sta.size()) sta.pop_back();
}else{
sta.pb(s1[i]);
}
}
scanf("%s",s2);
int l2=strlen(s2);
int l=1,r=1,ans=1;
rep(i,0,l2){
if(s2[i]=='U'){
if(sta.size()){
char last=sta[sta.sz()-1];
sta.pop_back();
if(last=='L'){
add_mod(r,1);
add_mod(ans,1);
}else{
add_mod(l,1);
add_mod(ans,1);
}
}
}else if(s2[i]=='L'){
add_mod(r,l);
add_mod(ans,l);
}else{
add_mod(l,r);
add_mod(ans,r);
}
}
printf("Case %d: %d\n",++kase,ans);
}
return 0;
}