Codeforces Round #406 C. Berzerk(搜索)

来源:互联网 发布:晓风软件 编辑:程序博客网 时间:2024/05/22 23:30

Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer.

In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There’s a monster in one of the planet. Rick and Morty don’t know on which one yet, only that he’s not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario.

Each one of them has a set of numbers between 1 and n - 1 (inclusive). Rick’s set is s1 with k1 elements and Morty’s is s2 with k2 elements. One of them goes first and the player changes alternatively. In each player’s turn, he should choose an arbitrary number like x from his set and the monster will move to his x-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins.

Your task is that for each of monster’s initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game.

题意

此题主要是求对于假设怪物(monster)初始位置分别在 2, 3, …, n 时,Rick 先手及 Morty 先手进行博弈的结果。

分析

此题若从正面试图结合博弈论的想法去解决,会受限于 Loop 状态导致各种不正常的状态。

此处记 (idx, pos) 表示当怪物处于 pos 位置时,轮到 idx {Rick: 0; Morty: 1} 的情况。

为方便进行取模操作,将标号 1~n 均减 1 ,视作位置 0~(n-1)

解决此题的重点在于从结束状态 (0, 0)(1, 0) 进行回溯。

已知当怪物处于位置 0 且轮到 Rick 时,即状态 (0, 0) 时,Rick 处于必输态 Lose 。该状态的前置状态有 (1, s[idx=1][j]) 且为必胜态…

在对各种状态的枚举过程中,若 (idx, pos) 为必输态,则其所有前置状态均为必胜态。若 (idx, pos) 为必胜态,则当其前置状态 (!idx, nxt) 的所有后续状态均为必胜态时,状态 (!idx, nxt) 为必输态。

游戏的结束状态有且两种 (0, 0)(1, 0) ,故所有未搜索到的状态均为 Loop

代码

#include<bits/stdc++.h>using namespace std;int n, s[2][7010], k[2], cnt[2][7010];bool vis[2][7010], ans[2][7010];void solve(int idx, int pos){    vis[idx][pos] = 1;    for(int i=0, nxt;i<k[!idx];i++)    {        nxt = (pos + n - s[!idx][i]) % n;        if(nxt == 0)    continue;        if(vis[!idx][nxt])  continue;        if(ans[idx][pos] && ++cnt[!idx][nxt] == k[!idx])            solve(!idx, nxt);        else if(ans[idx][pos] == false)            ans[!idx][nxt] = true,            solve(!idx, nxt);    }}void pt(int idx, int pos) {    if(vis[idx][pos]==0)    printf("Loop ");    else        printf("%s ", ans[idx][pos] ? "Win" : "Lose");}int main(){    scanf("%d",&n);    for(int idx=0;idx<2;idx++)    {        scanf("%d",&k[idx]);        for(int i=0;i<k[idx];i++)            scanf("%d",&s[idx][i]);    }    solve(0, 0);    solve(1, 0);    for(int idx=0;idx<2;idx++)    {        for(int i=1;i<n;i++)            pt(idx, i);        printf("\n");    }}
0 0