HDU 3088 WORM

Description

一个虫子,有三种颜色,rgb,它可以执行一种变换,两个不同的颜色变成一个相同的颜色,问,能不能变成全是一种颜色

Algorithm

BFS,每次变变变
同时用三进制r = 0, g = 1, b = 2来记录每一次的情况。

Code

#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
struct V
{
  string s;
  int step, h;
};
const int maxh = 1e6;
bool h[maxh];
int main()
{
  int n;
  cin >> n;
  for (int i = 0; i < n; i++)
  {
    memset(h, 0, sizeof(h));
    string s;
    cin >> s;
    queue<V> q;
    V t;
    t.s = s;
    t.step = 0;
    int ss = 1; // 阶
    int hh = 0; // 3进制表示值
    for (int j = 0; j < s.size(); j++)
    {
      if (s[j] == 'g') hh += ss;
      if (s[j] == 'b') hh += ss * 2;
      ss *= 3;
    }
    h[hh] = true;
    q.push(t);
    int ans = -1;
    while (!q.empty())
    {
      V now = q.front();
      q.pop();
      //检验是否同色
      bool flag = true;
      for (int j = 1; j < now.s.size(); j++)
        if (now.s[j] != now.s[j - 1])
        {
          flag = false;
          break;
        }
      if (flag)
      {
        ans = now.step;
        break;
      }
      //变变变
      for (int j = 1; j < now.s.size(); j++)
        if (now.s[j] != now.s[j - 1])
        {
          V t;
          t.s = now.s;
          char ch;
          if (now.s[j] == 'r' && now.s[j - 1] == 'g') ch = 'b';
          if (now.s[j] == 'g' && now.s[j - 1] == 'r') ch = 'b';
          if (now.s[j] == 'r' && now.s[j - 1] == 'b') ch = 'g';
          if (now.s[j] == 'b' && now.s[j - 1] == 'r') ch = 'g';
          if (now.s[j] == 'g' && now.s[j - 1] == 'b') ch = 'r';
          if (now.s[j] == 'b' && now.s[j - 1] == 'g') ch = 'r';
          t.s[j] = ch;
          t.s[j - 1] = ch;
          ss = 1; // 阶
          hh = 0; // 3进制表示
          for (int k = 0; k < t.s.size(); k++)
          {
            if (t.s[k] == 'g') hh += ss;
            if (t.s[k] == 'b') hh += ss * 2;
            ss *= 3;
          }
          if (!h[hh])
          {
            h[hh] = true;
            t.step = now.step + 1;
            q.push(t);
          }
        }
    }
    if (ans == -1) cout << "No solution!" << endl; else cout << ans << endl;
  }
}

你可能感兴趣的:(HDU 3088 WORM)