zoukankan      html  css  js  c++  java
  • hdu 1195 Open the Lock

    Problem - 1195

      一个全排列的搜索题,开始的时候看错题,没发觉是两个相邻的数才可以交换。计算交换次数可以用冒泡排序来模拟,从而算两个状态间要多少次交换才能达到。

    代码如下:

    View Code
     1 #include <cstdio>
     2 #include <cstring>
     3 #include <iostream>
     4 #include <algorithm>
     5 
     6 using namespace std;
     7 
     8 #define REP(i, n) for (int i = 0; i < (n); i++)
     9 #define REP_1(i, n) for (int i = 1; i <= (n); i++)
    10 #define INC(i, a, b) for (int i = (a); i <= (b); i++)
    11 #define DEC(i, a, b) for (int i = (a); i >= (b); i--)
    12 #define _clr(x) memset(x, 0, sizeof(x))
    13 
    14 template <class T> T sqr(T x) {
    15     return x * x;
    16 }
    17 typedef long long LL;
    18 const int N = 1e5 + 100;
    19 const LL linf = 0x5555555555555555ll;
    20 const int inf = 0x55555555;
    21 
    22 int arr[5], best;
    23 char str[2][6];
    24 
    25 int diff(char a, char b) {
    26     int d = max(a, b) - min(a, b);
    27     return min(d, 9 - d);
    28 }
    29 
    30 int cal() {
    31     int ret = 0;
    32     REP(i, 4) ret += diff(str[0][arr[i]], str[1][i]);
    33     return ret;
    34 }
    35 
    36 int cal(int *a) {
    37     int tmp[4];
    38     REP(i, 4) tmp[i] = a[i];
    39     int ret = 0;
    40     bool chg = true;
    41     while (chg) {
    42         chg = false;
    43         REP(i, 3) {
    44             if (tmp[i] > tmp[i + 1]) { swap(tmp[i], tmp[i + 1]); chg = true; ret++;}
    45         }
    46     }
    47     return ret;
    48 }
    49 
    50 void dfs(int l, int r) {
    51     if (l == r) {
    52         best = min(best, cal() + cal(arr));
    53         return ;
    54     }
    55     INC(i, l, r) {
    56         swap(arr[i], arr[l]);
    57         dfs(l + 1, r);
    58         swap(arr[i], arr[l]);
    59     }
    60 }
    61 
    62 int main() {
    63 //    freopen("in", "r", stdin);
    64     int T;
    65     cin >> T;
    66     while (T--) {
    67         REP(i, 2) cin >> str[i];
    68         REP(i, 4) arr[i] = i;
    69         best = inf;
    70         dfs(0, 3);
    71         cout << best << endl;
    72     }
    73     return 0;
    74 }

    ——written by Lyon

  • 相关阅读:
    去掉安装程序被挂起,要重新启动电脑
    为什么要关闭数据库连接,可以不关闭吗?
    读取Excel异常定义了过多字段的解决方法
    关于打开ILDASM的方法
    SQL Server数据类型
    C++的MFC,与C#的.NET
    javascript数据类型
    日志记录组件[Log4net]详细介绍
    Xml的读取
    yield让代码更加简洁
  • 原文地址:https://www.cnblogs.com/LyonLys/p/hdu_1195_Lyon.html
Copyright © 2011-2022 走看看