It's not a Bug, it's a Feature! UVA - 658

本文介绍了一种使用状态转移方法寻找修复一系列Bug所需的最短时间的算法。通过二进制表示Bug的状态,结合优先队列进行状态转移,确保找到从初始状态到所有Bug修复完毕状态的最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一道简单的题目,利用二进制的每一位来对应Bug的每一位,然后进行状态转移即可,在状态转移之前要记得判断当前的bug的情况是否满足转移的要求,同时在状态转移之后要判断转移的时间是否更短了,如果更短要记得更新,并且要将相应的状态放到队列当中,为下一次转移的操作做铺垫,具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;

const int INF = 0x3f3f3f3f;

const int Inf = 1 << 20;
int dist[Inf + 10];

class Bug{
public:
	int dist, bug;
	bool operator< (const Bug& a)const{
		return dist > a.dist;
	}
};

class Solve{
public:
	int n, m;
	string before[110], after[110];
	int Time[110];
	void Init(){
		memset(dist,INF,sizeof(dist));
		for (int i = 0; i < m; i++){
			cin >>Time[i]>> before[i] >> after[i];
		}
	}

	int Deal(){
		Init();
		priority_queue<Bug, vector<Bug>> pq;
		Bug start;
		start.bug = (1 << n) - 1;
		start.dist = 0;
		pq.push(start);
		while (!pq.empty()){
			Bug temp = pq.top();
			if (temp.bug == 0) return temp.dist;
			pq.pop();
			for (int i = 0; i < m; i++){
				bool use = true;
				for (int j = 0; j < n; j++){
					if (before[i][j] == '-' && (temp.bug&(1 << j))){ use = false; break; }
					if (before[i][j] == '+'&&!(temp.bug&(1 << j))){ use = false; break; }
				}
				if (!use) continue;
				Bug nxt=temp;
				for (int j = 0; j < n; j++){
					if (after[i][j] == '+') nxt.bug |= (1 << j);
					if (after[i][j] == '-') nxt.bug &= ~(1 << j);
				}
				nxt.dist += Time[i];
				int& amount = dist[nxt.bug];
				if (amount<0||amount > nxt.dist){
					amount = nxt.dist;
					pq.push(nxt);
				}
			}
		}
		return -1;
	}
};

int main(){
	Solve a;
	int Case = 0;
	while (cin >> a.n >> a.m){
		if (a.n == 0 && a.m == 0) break;
		Case++;
		int res = a.Deal();
		cout << "Product " << Case << endl;
		if (res == -1){
			cout << "Bugs cannot be fixed.\n\n";
		}
		else{
			cout << "Fastest sequence takes "<<res<<" seconds.\n\n";
		}
	}
	return 0;
}

/*
3 3
1 000 00-
1 00- 0-+
2 0-- -++

4 1
7 0-0+ ---0
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值