4238: Save the Princess
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 1833 Solved: 865
Description
There were N people standing in a row, including the princess and N-1 robbers,numbered 1 to N from left to right. You already know the princess’ number is K. BH and LYF must kill robbers before meeting the princess. BH and LYF were both very powerful, they took turns killing the robbers. On each turn, a man could kill the left most robber or kill the right most robber. The massacre would end until there was a man to save the princess. The princess would marry the man who saved her first. Assume that BH and LYF kill optimally and LYF kill first, determine the princess would be married to who.
Input
The first line of the input contains an integer T(T <= 500) which means the number of test cases.
For each test case, there are two integers n(3 <= n <= 1000000000) and k(1 < k < n) which mean the number of robbers and the princess’ position.
Output
Output a single line: if the princess would be married to the prince, print ”BH”(without quote), otherwise print ”LYF”(without quote).
Sample Input
5 3 2 4 3 5 2 6 4 6 5
Sample Output
BH LYF BH LYF LYF
原题链接:http://oj.acm.zstu.edu.cn/JudgeOnline/problem.php?id=4238
题意:王子和侍卫一起去救公主,公主和强盗排成一排,给你这一排的总人数和公主的在这一排的第几个位置,侍卫和王子一个轮一个杀强盗,谁先到公主的位置谁和公主结婚
,规定侍卫先开始杀。每个人杀之前可以选择从左边还是从右边。
思路:这是一个博弈论的,谁先到公主旁边,谁就赢。仔细看一下数据范围,公主是不可能站在边上的,然后侍卫和王子在轮到自己杀的时候,可以随意选择左右边的。所以
除了公主(n-1)个人,侍卫先开始,那如果(n-1)是奇数,只剩公主时轮到侍卫,(n-1)是偶数的时候,只剩公主的时候轮到王子。
参考翻译:http://blog.csdn.net/qqchanmingdexiaji/article/details/53289511
AC代码:
/** * 行有余力,则来刷题! * 博客链接:http://blog.csdn.net/hurmishine * */ #include <cstdio> #include <iostream> using namespace std; int main() { int T; //freopen("4238.txt","r",stdin); //freopen("me.txt","w",stdout); cin>>T; int n,k; while(T--) { cin>>n>>k; if((n-1)%2==0) cout<<"BH"<<endl; else cout<<"LYF"<<endl; } return 0; }
标程:
题型:博弈题,找规律题。
题解:可以使用SG函数打表小数据找规律,发现n为偶数时答案是LYF,奇数就是BH。
证明:设公主左边x个强盗,右边y个强盗。令m=x+y,每一轮都使得m减1,终态就是x=1,y=1,也就是答案和m的奇偶性有关。
代码:
#include <bits/stdc++.h>
int main() {
//freopen("read.in", "r", stdin);
//freopen("write.out", "w", stdout);
int T;
scanf("%d", &T);
while (T--) {
int n, k;
scanf("%d%d", &n, &k);
printf("%s\n", n & 1 ? "BH" : "LYF");
}
return 0;
}
#include <bits/stdc++.h>
const int N = 1e3 + 5;
int sg[N][N];
bool vis[N];
int SG(int x, int y) {
if (sg[x][y] != -1) return sg[x][y];
int a = -1, b = -1;
if (x > 1) a = SG(x-1, y);
if (y > 1) b = SG(x, y-1);
int vis[2] = {0};
if (a != -1) vis[a] = true;
if (b != -1) vis[b] = true;
int ret = 0;
while (vis[ret]) ret++;
return sg[x][y] = ret;
}
int main() {
memset(sg, -1, sizeof(sg));
sg[1][1] = 0;
int T;
scanf("%d", &T);
while (T--) {
int n, k;
scanf("%d%d", &n, &k);
printf("%s\n", SG(k-1, n-k) ? "LYF" : "BH");
}
return 0;
}