题目链接:点击打开链接
题意:补丁在修正bug时,有时会产生新的bug。现在有n(n<=20)个bug和m(m<=100)个补丁,每个补丁用两个长度为n的字符串描述。分别表示打补丁之前状态(+表示该bug必须存在,-表示必须不存在,0表示无所谓)和打补丁之后状态(+表示该bug必须存在,-表示必须不存在,0表示和之前该位置状态相同)。每个补丁都有执行时间。求使所有bug都消除的最少耗时。同一个补丁可以打多次。
思路:因为n很小,考虑状压dp。每个状态由其前驱状态得到。但是只能用dp的思想,因为状态多次转移之后可能回到之前的状态。正确的方法是将每一个二进制状态看做一个点,求图上的最短路。
点最多有1<<n个,并不能像普通dij一样枚储存以由该状态到达的点。方法是枚举每一个补丁,找出由该状态可以到达的点。
AC代码
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include<iostream>
#define ll long long
using namespace std;
typedef long long LL;
const LL INF = 100000000000000;
const int N = 105;
int n,m,vis[1<<21];
struct node
{
int t;
char pre[22],aft[22];
} a[N];
struct point
{
int l,u;
point(int uu,int dd) :u(uu),l(dd) {}
bool operator < (const point p) const
{
return l>p.l;
}
};
LL d[1<<22],base[22];
void dijkstra(int s)
{
memset(vis,0,sizeof(vis));
d[s] = 0;
priority_queue<point>q;
q.push(point(s,0));
while(!q.empty())
{
point now = q.top();
q.pop();
int u = now.u;
if(vis[u]) continue;
vis[u] = 1;
for(int i = 0; i<m; i++)
{
bool flag = 1;
for(int j = 0; j<n; j++)
{
if(a[i].pre[j]=='+' && !((1<<j)&u) )
{
flag = 0;
break;
}
else if(a[i].pre[j]=='-' && (1<<j)&u)
{
flag = 0;
break;
}
}
if(flag)
{
int next = 0;
for(int j = 0; j<n; j++)
{
if(a[i].aft[j] =='+') next = next + base[j];
else if(a[i].aft[j]=='-') continue;
else next = next + (((1<<j) & u)? base[j]:0);
}
if(!vis[next] && d[u]+a[i].t<d[next])
{
d[next] = d[u] + a[i].t;
q.push(point(next,d[next]));
}
}
}
}
}
void init(int n)
{
for(int i =0; i<(1<<n); i++) d[i] = INF;
}
int main()
{
int cs = 0;
base[0] = 1;
for(int i = 1; i<=20; i++) base[i] = base[i-1] * 2;
while(~scanf("%d%d",&n,&m) && n+m)
{
init(n);
int s = 0;
for(int i = 0; i<n; i++) s = s*2 + 1;
for(int i = 0; i<m; i++)
{
scanf("%d%s%s",&a[i].t,a[i].pre,a[i].aft);
}
dijkstra(s);
if(d[0]>=INF) printf("Product %d\nBugs cannot be fixed.\n\n",++cs);
else printf("Product %d\nFastest sequence takes %lld seconds.\n\n",++cs,d[0]);
}
return 0;
}