| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
Re:思路一样 用STL自带的优先队列超时,无奈之下只能自己写一个堆。。。In Reply To:思路一样 用STL自带的优先队列超时,无奈之下只能自己写一个堆。。。 Posted by:zihuacs at 2010-08-21 21:20:35 兄弟,看看这个
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define MAXL 25
#define MAXNop 35
#define MAXNw 25
#define MAXS 1100000
struct queueNode{
int state;
int step;
friend bool operator<(queueNode A, queueNode B){
return (A.step > B.step);
}
};
struct operNode{
char method[MAXL];
int cost;
};
int bit[MAXL], len;
priority_queue<queueNode> Q;
operNode oper[MAXNop];
int exist[MAXS];
int btod(char *str){
int ans = 0;
for(int i = 0; i < len; ++ i){
ans += (str[i] - '0') * bit[i];
}
return ans;
}
int change(int num, int id){
for(int i = 0; i < len; ++ i){
switch (oper[id].method[i]){
case 'N': break;
case 'F': num ^= bit[i];
break;
case 'S': num |= bit[i];
break;
case 'C': if(num & bit[i]) num ^= bit[i];
break;
}
}
return num;
}
int bfs(int st, int ed, int nop){
while(!Q.empty()) Q.pop();
queueNode temp;
temp.state = st;
temp.step = 0;
Q.push(temp);
memset(exist, 0, sizeof(exist));
while(!Q.empty()){
queueNode h = Q.top();
Q.pop();
if(h.state == ed) return h.step;
for(int i = 0; i < nop; ++ i){
int num = change(h.state, i);
if(!exist[num] || exist[num] > h.step + oper[i].cost){
temp.state = num;
temp.step = h.step + oper[i].cost;
exist[num] = temp.step;
Q.push(temp);
}
}
}
return -1;
}
int main(){
int CASE, nop, nw, st, ed, head, tail, ans;
char str1[MAXL], str2[MAXL];
for(bit[0] = len = 1; len < 23; ++ len) bit[len] = bit[len - 1] * 2;
scanf("%d", &CASE);
while(CASE --){
scanf("%d %d %d", &len, &nop, &nw);
for(int i = 0; i < nop; ++ i) scanf("%s %d", oper[i].method, &oper[i].cost);
while(nw --){
scanf("%s %s", str1, str2);
st = btod(str1);
ed = btod(str2);
ans = bfs(st, ed, nop);
if(ans < 0) printf("NP");
else printf("%d", ans);
printf("%c", nw ? ' ' : '\n');
}
}
return 0;
}
360MS
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator