網絡流24題——軟件補丁問題

題目鏈接:https://www.luogu.org/recordnew/show/10501734

【問題分析】

求一個狀態到另一個狀態變換的最少費用,最短路徑問題。

【建模方法】

軟件的狀態用二進制位表示,第i位爲第i個錯誤是否存在。把每個狀態看做一個頂點,一個狀態應用一個補丁到達另一狀態,連接一條權值爲補丁時間的有向邊。求從初始狀態到目標狀態的最短路徑即可。

#include <bits/stdc++.h>
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<node> 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;
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章