例题11-6 这不是bug,而是特性(It's not a Bug, it's a Feature!, UVa 658)(隐式图+最短路+位运算)

题目https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=8&page=show_problem&problem=599

分析:

翻译

补丁在修正bug时,有时也会引入新的bug。假定有n(n≤20)个潜在bug和m(m≤100)个补丁,每个补丁用两个长度为n的字符串表示,其中字符串的每个位置表示一个bug。第一个串表示打补丁之前的状态(“-”表示该bug必须不存在,“+”表示必须存在,0表示无所谓),第二个串表示打补丁之后的状态(“-”表示不存在,“+”表示存在,0表示不变)。每个补丁都有一个执行时间,你的任务是用最少的时间把一个所有bug都存在的软件通过打补丁的方式变得没有bug。一个补丁可以打多次。
 

“+”表示有,因此每个位置都会有可能是“+”,次数状态最大有2^n个状态,题目要求将全是bug(也就是全是1)的状态转换成全是0的最少时间,状态转移能想到动态规划,但是再想一下就知道有些状态不止出现一次,这说明有环!,记忆搜会出现无限递归,但是状态转移可以向紫数上的第7章搜索(像那个倒水的问题),带环就可以将问题转换成图上的最短路(隐式图),枚举补丁,位运算判断是否可以在当前状态上打补丁,贴上lrj代码

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

struct Node {
  int bugs, dist;
  bool operator < (const Node& rhs) const {
    return dist > rhs.dist;
  }
};

const int maxn = 20;
const int maxm = 100 + 5;
const int INF = 1000000000;

int n, m, t[maxm], dist[1<<maxn], mark[1<<maxn];
char before[maxm][maxn + 5], after[maxm][maxn + 5];

int solve() {
  for(int i = 0; i < (1<<n); i++) { mark[i] = 0; dist[i] = INF; }
  priority_queue<Node> q;

  Node start;
  start.dist = 0;
  start.bugs = (1<<n) - 1;
  q.push(start);

  dist[start.bugs] = 0;
  while(!q.empty()) {
    Node u = q.top(); q.pop();
    if(u.bugs == 0) return u.dist;
    if(mark[u.bugs]) continue;
    mark[u.bugs] = 1;
    for(int i = 0; i < m; i++) {
      bool patchable = true;
      for(int j = 0; j < n; j++) {
        if(before[i][j] == '-' && (u.bugs & (1<<j))) { patchable = false; break; }
        if(before[i][j] == '+' && !(u.bugs & (1<<j))) { patchable = false; break; }
      }
      if(!patchable) continue;

      Node u2;
      u2.dist = u.dist + t[i];
      u2.bugs = u.bugs;
      for(int j = 0; j < n; j++) {
        if(after[i][j] == '-') u2.bugs &= ~(1<<j);
        if(after[i][j] == '+') u2.bugs |= (1<<j);
      }
      int& D = dist[u2.bugs];
      if(D < 0 || u2.dist < D) {
        D = u2.dist;
        q.push(u2);
      }
    }
  }
  return -1;
}

int main() {
  int kase = 0;
  while(scanf("%d%d", &n, &m) == 2 && n) {
    for(int i = 0; i < m; i++) scanf("%d%s%s", &t[i], before[i], after[i]);
    int ans = solve();
    printf("Product %d\n", ++kase);
    if(ans < 0) printf("Bugs cannot be fixed.\n\n");
    else printf("Fastest sequence takes %d seconds.\n\n", ans);
  }
  return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值