UVa279 - Spin(递推)

 Spin 
tex2html_wrap62tex2html_wrap64

A disk can be rotated between horizontal and vertical only if it is positioned over theindentation marked `0' and the disk on its right is vertical . The right-mostdisk can always rotate if it is in position `0' since it has no disk on its right.

The aim is to free the slide by moving it so its left edge aligns with the `Win' mark:

Your task is to write a program which will take several part-solved puzzles and computethe number of steps needed to move the slide to position `Win' for each puzzle.

Input

There will be several puzzles in the input file. The first line of the file willcontain an integer n specifying the number of puzzles. There will then be nlines, each of the form:

length orientations position

where length(length < 30) is an integer indicating the number of disks on theslide, orientations is a string of length characters from the set {h,v}giving the orientation of each disk from left to right, and position is an integerfrom 0 to length specifying the numbered mark which aligns with the left edge ofthe slide.

Output

For each puzzle, your program should output one integer on a line which counts theminimum number of steps needed to win the puzzle. A step is either a movement of theslide, one unit left or right, or the rotation of a disk.

Sample Input

2
2 vv 2
7 vhhhvhh 4

Output for the SampleInput

7
357

Diagram of the 1stPuzzle

用递推方法

#include <cstdio>
#include <iostream>
#include <string>

using namespace std;

const int N = 30;

typedef long long LL;

LL f[N + 5];
string orientation;
int length;
int position;

void init()
{
	f[0] = 0;
	for (int i = 1; i <= N; i++) {
		f[i] = f[i - 1] * 2 + 2 * i - 1;
	}
}

void input()
{
	cin >> length >> orientation >> position;
}

void solve()
{
	size_t len = orientation.length();

	LL ans = 0;
	int sign = 1;

	for (size_t i = 0; i < len; i++) {
		if (orientation[i] == 'v') {
			ans += sign * (f[length - i]);
			sign *= -1;
		}
	}

	ans += position + 1;
	cout << ans << endl;
}

int main(int argc, char **argv)
{
#ifndef ONLINE_JUDGE
	freopen("d:\\OJ\\uva_in.txt", "r", stdin);
#endif

	init();

	int t ;
	cin >> t;
	while (t--) {
		input();
		solve();
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值