您的位置:首页 > 编程语言 > Go语言

HackerRank - "Hexagonal Grid"

2015-07-20 12:15 597 查看
Interesting one.. It is more about data structure design actually. After you figure out how to represent cells, the DP formula will be very intuitive :)

Data structure: just interleave the 2 strings and form a bitset..

#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <bitset>
using namespace std;

#define MAX_LEN 201

bool calc(int n, string &n1, string &n2)
{
std::bitset<MAX_LEN> b;
vector<bool> dp(2 * n, false);
int last = 0;
for (int i = 0; i < n; i++)
{
b[i * 2] = n1[i] - '0';
if (!b[i * 2]) last = i * 2;
b[i * 2 + 1] = n2[i] - '0';
if (!b[i * 2 + 1]) last = i * 2 + 1;
}

for (int i = 0; i < 2 * n; i++)
{
if (b[i])
{
dp[i] = (i == 0) ? true: dp[i - 1];
continue;
}
// now b[i] is 0
bool prev = (i == 0 ? true : (dp[i - 1]));
if (!prev) continue;

bool next = false, nnext = false;
if (i < (2 * n - 1)) //
{
next = b[i + 1];
if (!next)
dp[i + 1] = true;
}
if (i < (2 * n - 2))
{
nnext = b[i + 2];
if (next && (!nnext))
dp[i + 2] = true;
}
}
return dp[last];
}

int main()
{
int t; cin >> t;
while (t--)
{
int n; cin >> n;
string n1, n2; cin >> n1 >> n2;
bool r = calc(n, n1, n2);
cout << (r ? "YES" : "NO") << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: