SPOJ - Linearian Colony【分解为子问题】

COLONY - Linearian Colony

no tags 

 

Description

Linearians are pecurliar creatures. They are odd in several ways:
  1. Every Linearian is either red or blue.
  2. A Linearian colony is a straight line, aligned N-S with the magentic field.
  3. A colony starts with single red Linearian.
  4. Every year, each Linearian produces an offspring of the opposite color. After birth, the parent moves just south of the offspring. (Since everyone is born at once, this does make for a lot of jostling, but everyone stays in order.)
So a colony grows as follows:
N ----------- S

Year 0: R
Year 1: BR
Year 2: RBBR
Year 3: BRRBRBBR
Year 4: RBBRBRRBBRRBRBBR
Given a year and a position along the N-S axis, determine what the color of the Linearian there will be.

Input

The first line is the year Y (0 <= Y <= 51).The second line is the position P from north to south, 0-indexed (0 <= P < 2^Y).

Ouput

The color of the Linearian, either red or blue.
InputInput
3
6
51
123456789012345
OutputOutput
blue
red
 


题意:第i个字符串 = 第i-1个字符串的翻转 + 第i-1个字符串。翻转(R->B, B->R)。求第n个字符串的第p个字符串是什么。

题解:分解为子问题即可。判断p在第n个字符串的前半部分还是后半部分,然后去递归求解子问题即可。

代码:

 

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cmath>
 4 #include <cstring>
 5 #include <map>
 6 #include <vector>
 7 #include <queue>
 8 #include <list>
 9 #include <cstdio>
10 #define rep(i,a,b) for(int (i) = (a);(i) <= (b);++ (i))
11 #define per(i,a,b) for(int (i) = (a);(i) >= (b);-- (i))
12 #define mem(a,b) memset((a),(b),sizeof((a)))
13 #define FIN freopen("in","r",stdin)
14 #define FOUT freopen("out","w",stdout)
15 #define IO ios_base::sync_with_stdio(0),cin.tie(0)
16 #define N 105
17 #define INF 0x3f3f3f3f
18 #define INFF 0x3f3f3f3f3f3f3f
19 typedef long long ll;
20 const ll mod = 1e8+7;
21 const ll eps = 1e-12;
22 using namespace std;
23 
24 int n;
25 ll p,dp[55];
26 
27 void fuc(){
28     dp[0] = 1;
29     rep(i, 1, 51){
30         dp[i] = dp[i-1]*2;
31     }
32 }
33 int dfs(int n, ll p){
34     if(n == 0) return 1;
35     if(p < dp[n-1])    return !dfs(n-1, p);
36     else
37         return dfs(n-1, p-dp[n-1]);
38 }
39 int main()
40 {
41     //FIN;
42     fuc();
43     while(cin >> n >> p){
44         cout << (dfs(n, p) == 1 ? "red" : "blue") << endl;
45     }
46     return 0;
47 }
View Code

 

 


posted on 2017-01-15 21:01  Jstyle  阅读(299)  评论(0编辑  收藏  举报

导航