Gym 100917L Liesbeth and the String 规律&&胡搞

本文解析了一道关于字符串操作的编程题,题目要求通过特定的字符串变换规则,计算从初始字符串长度缩短至1所需的最少操作次数。文章提供了一种有效的算法实现方案,并通过实例演示了如何使用该算法。

题目:

Description

standard input/output
Statements

Little Liesbeth likes to play with strings. Initially she got a string of length n, consisting of letters 'a' only.

Then Liesbeth performs next operations with the string:

  • If the first letter of the string is 'a', then she adds to the end of the string "bc", and after that removes first two letters of the string.
  • If the first letter of the string is 'b', then she adds to the end of the string 'a', and after that removes first two letters of the string.
  • If the first letter of the string is 'c', then she adds to the end of the string 'aaa" and after that removes first two letters of the string.

Liesbeth stops when she has the string of length 1. For example, if n = 4, she needs 6 operations :

Liesbeth found that for some n number of operations is too big, and its hard to understand if the process is finite. So she asked You to write the program to help her.

Input

First line of the input contains one integer n (2 ≤ n ≤ 106) — length of the initial string.

Output

Print one integer — number of operations needed to obtain string of length 1. If process is infinite, print  - 1 insteaSample Input

Input
4
Output
6
Input
3
Output
24


题目大意:给出一个字符串(只含a)的初始长度,做一下变换,求得到字符串长度为1时的步骤数,变换如下:
1.字符串首字母为a时 字符串末尾加bc 并删除前2个字符
2.字符串首字母为b时 字符串末尾加a 并删除前2个字符
3.字符串首字母为c时 字符串末尾加aaa 并删除前2个字符

题目思路:找规律,
当字符串长度为偶数时:经过n/2步变为只含bc长度为n的形式,再经过n/2步变成只含a长度为n/2的形式
当字符串长度为奇数时:经过(n+1)/2 步变为含c+k(bc)形式长度为n的串,在经过(n+1)/2步变成只含a长度为n/2*3+2的串

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<vector>
 5 #include<stdio.h>
 6 #include<stdlib.h>
 7 #include<queue>
 8 #include<math.h>
 9 #define INF 0x3f3f3f3f
10 #define MAX 10000005
11 #define Temp 1000000000
12 
13 using namespace std;
14 
15 int main()
16 {
17     long long n,sum;
18     while(scanf("%lld",&n)!=EOF)
19     {
20         sum=0;
21         while(n>1)
22         {
23             if(n%2==0)
24             {
25                 while(n>1 && n%2==0)
26                 {
27                     sum+=n;
28                     n/=2;
29                 }
30             }
31 
32             else
33             {
34                 while(n%2 && n>1)
35                 {
36                     sum+=(n/2+1);
37                     sum+=(n/2+1);
38                     n=n/2*3+2;
39                 }
40             }
41         }
42         printf("%lld\n",sum);
43     }
44     return 0;
45 }
View Code

 

 

 
      

转载于:https://www.cnblogs.com/alan-W/p/5927973.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值