| ||||||||||
| 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 | |||||||||
单调队列定义(附代码,wa和ac)我每次调用函数时候都会重新定义一次队列,相当于清空队列, 但为什么会wa,我如果定义在外面,每次清空一次队列,就会过
wa
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<cstring>
#include<cmath>
using namespace std;
const int maxn = 1000000;
int road[maxn];
int pr[maxn];
int bfs(int a, int b){
memset(pr, 0, sizeof(pr));
memset(road, 0, sizeof(road));
queue<int>Q;
Q.push(a);
road[a] = 1;
while(!Q.empty()){
int temp = Q.front(); Q.pop();
int xx[3] = {1, -1, temp};
for(int i = 0; i < 3; i++){
int dx = temp + xx[i];
if(road[dx] == false&&dx >= 0&&dx <= 100000){
pr[dx] = pr[temp] + 1;
road[dx] = 1;
Q.push(dx);
}
if(dx == b) return pr[dx];
}
if(temp == b) return pr[temp];
}
}
int main()
{
int a, b;
while(scanf("%d%d", &a, &b) != EOF){
//while(!Q.empty()) Q.pop();
int res = bfs(a, b);
printf("%d\n", res);
}
return 0;
}
ac代码
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<cstring>
#include<cmath>
using namespace std;
const int maxn = 1000000;
int road[maxn];
int pr[maxn];
queue<int>Q;
int bfs(int a, int b){
memset(pr, 0, sizeof(pr));
memset(road, 0, sizeof(road));
Q.push(a);
road[a] = 1;
while(!Q.empty()){
int temp = Q.front(); Q.pop();
int xx[3] = {1, -1, temp};
for(int i = 0; i < 3; i++){
int dx = temp + xx[i];
if(road[dx] == false&&dx >= 0&&dx <= 100000){
pr[dx] = pr[temp] + 1;
road[dx] = 1;
Q.push(dx);
}
if(dx == b) return pr[dx];
}
if(temp == b) return pr[temp];
}
}
int main()
{
int a, b;
while(scanf("%d%d", &a, &b) != EOF){
while(!Q.empty()) Q.pop();
int res = bfs(a, b);
printf("%d\n", res);
}
return 0;
}
求解决
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator