题目传送门:B. Blackboard Fibonacci
题目大意就是说:有一个 Bord 分为上下两层,刚开始的时候上层写了 0 下层写了 1.现在给你一个数,要你在经过 n 个操作之后得到这个数。操作分为两类:
1、把上层的数加到下层去,本次得到的数是下层的新数,本次的操作符是 B
2、把下层的数加到上层去,本次得到的数十上层的新数,本次的操作符是 T
经过 n 次操作之后,得到了一个数,还有一个操作序列,定义一个 mistake :操作序列中连续 T 或者 B 的个数,问在经过 n 次操作之后等否得到给定的数,如果能,输出 mistake 之最小的操作序列,如果不能,输出 IMPOSSIBLE
初一看没思路,觉得是一个规律或者 DP 之类的题,应该会有公式之类的,但一看觉得不对,操作的次数是可以达到 10^6 的级别,要求得到的数也是 10^6 的级别,一下没有想法了,思维短路了
反省:
当一种方法没有思路的时候,就想想搜索+剪枝,这道题明显不可能用DP来做了,干嘛还死在想怎么用DP来实现
解题方法:
这个方法是后来猛然醒悟的,就是裸的暴力,枚举第 n 次操作之后得到的 Bord 上的状态,然后 o(n) 的向上推上去,不过需要加一些剪枝,因为要你得到的数是在 10^6 的级别的,当操作次数很大的时候,基本上就不可能得到,所以一些强有力的剪枝很重要
剪枝1:Bord 的上层和下层相等时,如果他们不等于 1,那么这个状态必然是非法的
剪枝2:Bord 上的数出现负数的时候,肯定也是不合法的
剪枝3:Bord 的上层和下层的数相等并且都是 1 的时候,如果经历的操作不是 n-1 ,那么这个状态也是非法的
加上这三个剪枝,这道题就能够在 1s 内 AC 了。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <list>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef double DB;
typedef unsigned long long ULL;
typedef unsigned int Uint;
const int INT_INF=0x3fffffff;
const LL LL_INF=0x3fffffffffffffff;
const DB EPS=1e-9;
const DB PI=3.14159265358979323846;
const int N=1000010;
const int E=1000010;
#define PB push_back
#define MP make_pair
#define MH make_heap
#define PH push
int n, r;
char ans[N], temp[N];
int Max_ope;
int cal_ope()
{
int cnt=0;
for(int i=1; i<n; i++)
if(temp[i]==temp[i+1]) cnt++;
return cnt;
}
bool deal(int Top, int Bot)
{
for(int i=n; i>=1; i--)
{
if(Bot==Top && Bot!=1) return false;
if(Bot<0 || Top<0) return false;
if(Bot==Top && Bot==1 && i!=1) return false;
if(Top>=Bot)
{
Top-=Bot;
temp[i]='T';
}
else
{
Bot-=Top;
temp[i]='B';
}
}
if(Top==0 && Bot==1) return true;
else return false;
}
int main()
{
while(~scanf("%d%d",&n,&r))
{
Max_ope=INT_INF;
for(int i=1; i<=r; i++)
{
if(deal(i,r))
{
int cnt=cal_ope();
if(Max_ope>cnt && temp[1]=='T')
{
memcpy(ans,temp,n+1);
Max_ope=cnt;
}
}
if(deal(r,i))
{
int cnt=cal_ope();
if(Max_ope>cnt && temp[1]=='T')
{
memcpy(ans,temp,n+1);
Max_ope=cnt;
}
}
}
if(Max_ope==INT_INF) printf("IMPOSSIBLE\n");
else
{
printf("%d\n",Max_ope);
for(int i=1; i<=n; i++)
{
printf("%c",ans[i]);
if(i==n) printf("\n");
}
}
}
return 0;
}
CodeForces 217B Blackboard Fibonacci