您的位置:首页 > Web前端

uva_658 It's not a Bug, it's a Feature! Dijkstra(优先队列)

2012-07-18 19:34 387 查看
#include <cstdio>
#include <algorithm>
#include <queue> 
using namespace std;
#define N 21
#define M 101 
const int inf = 500000000; 
int pre[2][M], next[2][M]; 
int t[M];
int d[1<<N]; 
typedef pair<int, int> pii; 
void dijkstra(int n, int m)
{
       for (int i = 0; i < (1 << n); i++)d[i] = inf;
       priority_queue<pii, vector<pii>, greater<pii> > q; 
       d[(1 << n) - 1] = 0; 
       q.push(make_pair(0, (1 << n) - 1));
       while (!q.empty())
       {
              pii u = q.top();q.pop();
              int x = u.second;
              if (u.first != d[x])continue;
              for (int i = 0; i < m ; i++)if (((x | pre[0][i]) == x) && (x&pre[1][i])== x)
              {
                     int v = x | next[0][i];
                     v &= next[1][i];
                     if (d[x] + t[i] < d[v]) 
                     { 
                              d[v] = d[x] + t[i]; 
                              q.push(make_pair(d[v], v));
                     } 
              }
       } 
} 

       
int ca = 1; 
int main()
{
      int n, m;
      char b1
, b2
;
      while (scanf("%d %d", &n, &m) != EOF && (m + n))
      {
            for (int i = 0; i < m; i++)
            {
                   scanf("%d %s %s", t + i, b1, b2);
                   pre[0][i] = pre[1][i] = next[0][i] = next[1][i] = 0;
                   for (int j = 0; j < n; j++)
                   {
                         if (b1[j] == '+')pre[0][i] |= (1 << j);
                         if (b1[j] != '-')pre[1][i] |= (1 << j);
                         if (b2[j] == '+')next[0][i] |= (1 << j);
                         if (b2[j] != '-')next[1][i] |= (1 << j);
                   }
            }
            dijkstra(n, m);
            printf("Product %d\n", ca++); 
            if (d[0] == inf)puts("Bugs cannot be fixed.");
            else printf("Fastest sequence takes %d seconds.\n", d[0]);
            puts(""); 
      }
      return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: