网络流24题——软件补丁问题

题目链接:https://www.luogu.org/recordnew/show/10501734

【问题分析】

求一个状态到另一个状态变换的最少费用,最短路径问题。

【建模方法】

软件的状态用二进制位表示,第i位为第i个错误是否存在。把每个状态看做一个顶点,一个状态应用一个补丁到达另一状态,连接一条权值为补丁时间的有向边。求从初始状态到目标状态的最短路径即可。

#include 
using namespace std;
const int INF = 0x3f3f3f3f;
int B1[105],B2[105],F1[105],F2[105];
int n,m;
char str1[105],str2[105];
int cost[105];
bool vis[10000005];
struct node
{
    int state,cost;
    node(){}
    node(int _state,int _cost)
    {
        state = _state;
        cost = _cost;
    }
    bool operator < (const struct node& a) const
    {
        return cost > a.cost;
    }
};
int ans;
void BFS()
{
    priority_queue pq;
    pq.push(node(((1 << n) - 1),0));
    struct node t;
    int flag;
    while(!pq.empty()) {
        t = pq.top();
        pq.pop();
        if(vis[t.state]) continue;
        vis[t.state] = true;
        for(int i = 1; i <= m; i++) {
            flag = 0;
            for(int j = 1; j <= n; j++) {
                if( (B1[i] & (1 << (j - 1))) && !(t.state & (1 << (j - 1))) ) {
                    flag = 1;
                    break;
                }
            }
            if(flag) continue;
            flag = 0;
            for(int j = 1; j <= n; j++) {
                if( (B2[i] & (1 << (j - 1))) && (t.state & (1 << (j - 1))) ) {
                    flag = 1;
                    break;
                }
            }
            if(flag) continue;
            int _state = t.state;
            flag = 0;
            for(int j = 1; j <= n; j++) {
                if((F1[i] & (1 << (j - 1))) && (t.state & (1 << (j - 1)))) {
                    _state ^= (1 << (j - 1));
                }
            }
            for(int j = 1; j <= n; j++) {
                if((F2[i] & (1 << (j - 1))) && !(t.state & (1 << (j - 1)))) {
                    _state |= (1 << (j - 1));
                }
            }
            if(!_state) {
                ans = min(ans,t.cost + cost[i]);
            }
            pq.push(node(_state,t.cost + cost[i]));
        }
    }
}
int main(void)
{
    scanf("%d %d",&n,&m);
    for(int i = 1; i <= m; i++) {
        scanf("%d",&cost[i]);
        scanf("%s %s",str1,str2);
        for(int j = 0; j < n; j++) {
            if(str1[j] == '+') B1[i] |= (1 << (n - j - 1));
            if(str1[j] == '-') B2[i] |= (1 << (n - j - 1));
            if(str2[j] == '-') F1[i] |= (1 << (n - j - 1));
            if(str2[j] == '+') F2[i] |= (1 << (n - j - 1));
        }
    }
    ans = INF;
    BFS();
    printf("%d\n",ans == INF ? 0 : ans);
    return 0;
}


 

你可能感兴趣的:(ACM-图论)