analysis
这个是可以抽象为最短路问题的
用状态压缩来表示bug的有无(0没有,1有)
那么就可以把每个bug的状态表示的数看做点,然后就可以从(11111…111)开始,枚举每一个补丁,判断并且进行状态转移
跑一个dij后直接看0号点(00000…000)的距离就可以判断答案了
话说不要乱用map来hash,因为map的每一次操作都是logn的,我就是因为乱用map来Hash导致TLE。。。只有在操作数比较少的时候才适合用map
code
#include <bits/stdc++.h>
using namespace std;
#define loop(i,start,end) for(register int i=start;i<=end;++i)
#define anti_loop(i,start,end) for(register int i=start;i>=end;--i)
#define clean(arry,num) memset(arry,num,sizeof(arry))
#define ll long long
template<typename T>void read(T &x){
x=0;char r=getchar();T neg=1;
while(r>'9'||r<'0'){if(r=='-')neg=-1;r=getchar();}
while(r>='0'&&r<='9'){x=(x<<1)+(x<<3)+r-'0';r=getchar();}
x*=neg;
}
const int maxn=50;
const int maxm=150;
char patch[maxm][2][maxn];
ll cost[maxm];
int n,m;
int nfp;
//vector<ll>dis;
ll dis[(1<<21)+10];
struct node{
int e;
ll w;
node():e(0),w(0){}
node(int e,int w):e(e),w(w){}
friend bool operator<(node a,node b){
return a.w>b.w;
}
};
inline bool check(node f,int acc){
int state=f.e;
loop(i,0,n-1)
if((patch[acc][0][i]=='-'&&(state&(1<<i)))||(patch[acc][0][i]=='+'&&(state&(1<<i))==0))
return false;
return true;
}
inline int update(node f,int acc){
int state=f.e;
loop(i,0,n-1){
if(patch[acc][1][i]=='+')
state=state|(1<<i);
else if(patch[acc][1][i]=='-')
if(state&(1<<i))
state=state^(1<<i);
}
return state;
}
priority_queue<node>q;
void dijkstra(){
q.push(node((1<<n)-1,0));
dis[(1<<n)-1]=0;
while(q.empty()==false){
node f=q.top();
int staf=f.e;
q.pop();
loop(i,1,m){
if(check(f,i)){
int v=update(f,i);
if(v==staf)
continue;
if(dis[v]>dis[f.e]+cost[i]){
dis[v]=dis[f.e]+cost[i];
q.push(node(v,dis[v]));
}
}
}
}
if(dis[0]>=0x3f3f3f3f3f3f3f3f)
printf("Bugs cannot be fixed.\n");
else printf("Fastest sequence takes %lld seconds.\n",dis[0]);
}
int main(){
int cnt=0;
while(++cnt){
if(cnt==24){
int tttt=0;
}
read(n);
read(m);
if(n==0&&m==0)
break;
if(cnt-1)
printf("\n");
nfp=0;
clean(dis,0x3f);
printf("Product %d\n",cnt);
loop(i,1,m){
read(cost[i]);
scanf("%s",patch[i][0]);
getchar();
scanf("%s",patch[i][1]);
}
dijkstra();
}
printf("\n");
return 0;
}