poj1482(隱式圖求最短路),poj1482短路
題目連結
題意:補丁在修正bug時,有時也會引入新的bug。假定有n個潛在的bug m個補丁,每個補丁用兩個長度為n的字串表示,其中字串的每個位置表示一個bug,第一個串表示打補丁之前的狀態('-'表示該bug必須不存在,’+‘表示必須存在,0表示無所謂,第二個串表示打補丁之後的狀態(-'表示不存在,’+‘表示存在,0表示不變)。每個補丁都有一個執行時間,你的任務使用最少的時間把一個bug都存在的軟體通過打補丁的方式變得沒有bug。一個補丁可以打多次。
解法:狀壓表示每個補丁的存在與否。隱式搜尋,會有很多狀態根本搜不到,spfa直接搜尋即可。對於每次都枚舉使用所有的補丁修補並鬆弛得到的狀態。
代碼:
/******************************************************* @author:xiefubao*******************************************************/#pragma comment(linker, "/STACK:102400000,102400000")#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <queue>#include <vector>#include <algorithm>#include <cmath>#include <map>#include <set>#include <stack>#include <string.h>//freopen ("in.txt" , "r" , stdin);using namespace std;#define eps 1e-8#define zero(_) (abs(_)<=eps)const double pi=acos(-1.0);typedef long long LL;const int Max=10100000;const LL INF=0x3FFFFFFF;int state[(1<<20)+10];int n,m;struct bug{ int cost; char start[22]; char end[22];} bugs[1200];bool operator<(const bug& a,const bug& b){ return a.cost<b.cost;}int que[Max];bool rem[(1<<20)+10];int getstate(int st,int j){ for(int i=0; i<n; i++) { if(bugs[j].start[i]=='-'&&(st&(1<<i))) return -1; if(bugs[j].start[i]=='+'&&!(st&(1<<i))) return -1; } int re=0; for(int i=0; i<n; i++) { if(bugs[j].end[i]=='+') re|=(1<<i); if(bugs[j].end[i]=='0') re|=st&(1<<i); } return re;}int main(){ int kk=1; while(cin>>n>>m) { if(n==0&&m==0) break; for(int i=0; i<m; i++) scanf("%d%s%s",&bugs[i].cost,bugs[i].start,bugs[i].end); sort(bugs,bugs+m); memset(state,-1,sizeof state); memset(rem,0,sizeof rem); state[(1<<n)-1]=0; rem[(1<<n)-1]=1; int left=0,right=1; que[0]=(1<<n)-1; while(left<right) { //cout<<left<<endl; int t=que[left++]; for(int i=0; i<m; i++) { int st=getstate(t,i); if(st!=-1&&(state[st]==-1||state[st]>state[t]+bugs[i].cost)) { state[st]=state[t]+bugs[i].cost; if(!rem[st]) que[right++]=st,rem[st]=1; } } rem[t]=0; } printf("Product %d\n",kk++); if(state[0]==-1) puts("Bugs cannot be fixed."); else { printf("Fastest sequence takes %d seconds.\n",state[0]); } cout<<endl; } return 0;}