【状压DP】【cofun1374】trip

【cofun1374】trip

这里写图片描述


  • 分析:
  • 把宝藏当做需经过的点,转为TSP问题,宝藏数<= 13,考虑状压DP。
    ①bfs出宝藏,起点,终点之间的距离。
    ②把起点,宝藏,终点压进二进制(0:该宝藏已取到/ 1:该宝藏未取到),状压DP转移方程:
s[i][j] = min(s[i][j], s[i - (1 << j)][l] + d[l][j]);

s[i][j]:状态为i时最后取到第j个宝藏的最少步数。

【现在整理看来还蛮简单易懂的= =然鹅记得那天因为变量问题调了一下午QVQQQ太蠢了5555~


  • 代码:
#include <bits/stdc++.h>
 using namespace std;

 const int g[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
 struct info{
    int x, y;
 }f[1005], e[15];
 int n, i, j, l, ne, t[35][35], d[15][15], dd[35][35], s[1 << 15][15];
 char c;

 inline void bfs(int k)
 {
    int head = 1,tail = 1, x, y, i;

    memset(dd, 0x3f, sizeof(dd));
    f[1].x = e[k].x, f[1].y = e[k].y;
    dd[f[1].x][f[1].y] = 0;
    t[f[1].x][f[1].y] = 1;

    for(; head <= tail; head ++)
        for(i = 0; i < 4; i ++)
        {
            x = f[head].x + g[i][0], y = f[head].y + g[i][1];
            if (x && x <= n && y && y <= n)
                if (t[x][y] != 1)
                {
                    f[++ tail].x = x, f[tail].y = y;
                    dd[x][y] = dd[f[head].x][f[head].y] + 1;
                    t[x][y] = 1;
                 }
          }

    for(i = 1; i <= tail; i ++)
        t[f[i].x][f[i].y] = 0;
    for(i = 0; i < ne; i ++)
        d[k][i] = dd[e[i].x][e[i].y];
 }

 int main()
 {

    scanf("%d\n", &n);
    for(i = 1; i <= n; i ++)
    {
        for(j = 1; j <= n; j ++)
        {
            scanf("%c", &c);
            if (c == '1') t[i][j] = 1;
            if (c == '2' && (i != 1 || j != 1) && (i != n || j != n))
                e[++ ne].x = i, e[ne].y = j;
         }
        scanf("\n");
     }
    //读入 
    memset(d, 0x3f, sizeof(d));
    e[0].x = e[0].y = 1;
    e[++ ne].x = n, e[ne].y = n;
    ne ++;
    for(i = 0; i < ne; i ++) bfs(i);
    //初始化,bfs出距离 
    memset(s, 0x3f, sizeof(s));
    s[1][0] = 0;
    for(i = 2; i < 1 << ne; i ++)
        for(j = 0; j < ne && (1 << j) <= i; j ++)
        if (i & (1 << j))
            for(l = 0; l < ne && (1 << l) <= i; l ++)
            if (l != j  && (i & (1 << l)))
                s[i][j] = min(s[i][j], s[i - (1 << j)][l] + d[l][j]);
    //状压DP 
    if (s[(1 << ne) - 1][ne - 1] == 0x3f3f3f3f)
        printf("No Solution");
    else
        printf("%d", s[(1 << ne) - 1][ne - 1]);
    //输出 
    return 0;

 }

推荐一个人呗【捂脸】,妥妥的男神→慕寒
沉迷他的每一首歌~喜欢他的心情不可说不可说XDD嘘。
(^o^)/~各位小伙伴们快来成为情敌哇~~~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值