标签:
UVA - 658 It’s not a Bug, it’s a Feature!(优先队列Dijkstra)
题目大意:补丁和漏洞之间的修复问题。有n种漏洞,m种补丁,接着给你m行代表的是m种补丁使用的情况。前面的n个字符表示的是补丁的使用前提,后面的n个字符表示的是补丁使用完后的漏洞状况。字符‘0’代表的是这个漏洞存不存在都没关系,‘+’代表的是这个漏洞存在或者出现, ‘-’代表的是消失或者是不存在。使用每种补丁都需要时间,一开始这些漏洞都是存在的,问最少花多少的时间能够把这些漏洞都消灭。
解题思路:因为有‘0’这样的情况,所以需要把不确定的情况暴力的转化为确定的情况,然后用2进制数来表示目前漏洞的状态,‘-’用1代表。’+‘用0代表。转化成0到2^n - 1的最短路问题。
代码:
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
typedef pair<int, int> pii;
priority_queue<pii, vector<pii>, greater<pii> > q;
const int maxn = 25;
const int maxm = (1<<20) + 5;
const int INF = 0x3f3f3f3f;
struct State {
int u;
int d;
};
vector<State> G[maxm];
char st1[maxn], st2[maxn];
int d[maxm];
int change (int n, char* st) {
int ans = 0;
for (int i = 0; i < n; i++) {
ans = (ans<<1);
if (st[i] == ‘-‘)
ans |= 1;
}
return ans;
}
void add_bug (int num1, int num2, int d) {
State st;
st.u = num2;
st.d = d;
G[num1].push_back(st);
}
inline void dfs (int n, int k, int t) {
if (k == n) {
int num1 = change(n, st1);
int num2 = change(n, st2);
add_bug(num1, num2, t);
return;
}
char tmp;
if (st1[k] == ‘0‘) {
st1[k] = ‘-‘;
tmp = st2[k];
if (st2[k] == ‘0‘)
st2[k] = ‘-‘;
dfs(n, k + 1, t);
st2[k] = tmp;
st1[k] = ‘+‘;
tmp = st2[k];
if (st2[k] == ‘0‘)
st2[k] = ‘+‘;
dfs(n, k + 1, t);
st2[k] = tmp;
st1[k] = ‘0‘;
} else {
tmp = st2[k];
if (st2[k] == ‘0‘)
st2[k] = st1[k];
dfs(n, k + 1, t);
st2[k] = tmp;
}
}
void read_Graph (int n, int m) {
int t;
int T = 1 << n;
for (int i = 0; i < T; i++)
G[i].clear();
for (int i = 0; i < m; i++) {
scanf ("%d%s%s", &t, st1, st2);
dfs(n, 0, t);
}
}
int Dijkstra (int n) {
int T = 1 << n;
for (int i = 1; i < T; i++)
d[i] = INF;
d[0] = 0;
q.push(make_pair(d[0], 0));
pii cur;
int u, v, w;
while (!q.empty()) {
cur = q.top();
q.pop();
u = cur.second;
if (cur.first != d[u]) continue;
for (int i = 0; i < G[u].size(); i++) {
v = G[u][i].u;
w = G[u][i].d;
if (d[v] > d[u] + w) {
d[v] = d[u] + w;
q.push(make_pair(d[v], v));
}
}
}
return d[T-1];
}
int main () {
int n, m, cas = 0;
printf ("%d\n", INF);
while (scanf ("%d%d", &n, &m) && (n || m)) {
read_Graph(n, m);
int ans = Dijkstra(n);
printf ("Product %d\n", ++cas);
if (ans == INF)
printf ("Bugs cannot be fixed.\n\n");
else
printf ("Fastest sequence takes %d seconds.\n\n", ans);
}
return 0;
}
UVA - 658 It’s not a Bug, it’s a Feature!(优先队列Dijkstra)
标签:
原文地址:http://blog.csdn.net/u012997373/article/details/44152101