易错点——queue中的入队出队
哎呀呀呀呀呀,queue没学好就是不行啊,每次都把队列想象成头进尾出,然后就尴尬了。
queue前期最大的用处就是BFS了,哎,每次BFS都去访问queue.back()怎么能对啊,最重要的还不是这个,是我每写一次就忘一次,这BFS还怎么写啊所以今天就吧这个错误记录到博客上,以免以后再犯。
这题我做了好久才发现这个错误,尴尬。
题目网址:微软大楼设计方案(戳我)
错误的代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<cstring>
int gox[4] = {0,1,0,-1},goy[4] = {1,0,-1,0},num[1001][1001],f[1001][1001],indexx[1001],indexy[1001],n,m,k;
const int inf = 0x3f3f3f3f;
int get_ans(int x1,int y1,int x2,int y2)
{
std::queue<int> x;
std::queue<int> y;
std::queue<int> deep;
x.push(x1);y.push(y1);deep.push(0);
f[x1][y1] = 1;
while(!x.empty())
{
int tempx = x.back(),tempy = y.back(),tempdeep = deep.back();
x.pop();y.pop();deep.pop();
for(int i = 0;i<4;i++)
{
int temp1 = tempx+gox[i],temp2 = tempy+goy[i];
if(num[temp1][temp2]==0||f[temp1][temp2]==1)continue;
f[temp1][temp2] = 1;
if(temp1==x2&&temp2==y2)return tempdeep+1;
x.push(temp1);y.push(temp2);deep.push(tempdeep+1);
}
}
return inf;
}
void change(int l,int h)
{
for(int i = 1;i<=h;i++)
num[l][i] = 1;
}
int main()
{
// freopen("code.in","r",stdin);
// freopen("code.out","w",stdout);
std::cin>>n>>k;
for(int i = 1;i<=n;i++)
{
int a;
std::cin>>a;
change(i,a);
}
std::cin>>m;
for(int i = 1;i<=m;i++)
{
int a,b;
std::cin>>a>>b;
indexx[i] = a;indexy[i] = b;
}
int ans = 0;
for(int i = 1;i<=m;i++)
for(int j = i+1;j<=m;j++)
{
memset(f,0,sizeof(f));
if(get_ans(indexx[i],indexy[i],indexx[j],indexy[j])<=k)
{
ans++;
}
}
std::cout<<ans;
// std::cout<<get_ans(3,1,4,3);
// fclose(stdin);
// fclose(stdout);
return 0;
}
就是因为那个back啊啊啊啊啊啊,浪费了我好几个小时啊啊啊啊啊。
正确代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<cstring>
int gox[4] = {0,1,0,-1},goy[4] = {1,0,-1,0},num[1001][1001],f[1001][1001],indexx[1001],indexy[1001],n,m,k;
const int inf = 0x3f3f3f3f;
int get_ans(int x1,int y1,int x2,int y2)
{
std::queue<int> x;
std::queue<int> y;
std::queue<int> deep;
x.push(x1);y.push(y1);deep.push(0);
f[x1][y1] = 1;
while(!x.empty())
{
int tempx = x.front(),tempy = y.front(),tempdeep = deep.front();
x.pop();y.pop();deep.pop();
for(int i = 0;i<4;i++)
{
int temp1 = tempx+gox[i],temp2 = tempy+goy[i];
if(num[temp1][temp2]==0||f[temp1][temp2]==1)continue;
f[temp1][temp2] = 1;
if(temp1==x2&&temp2==y2)return tempdeep+1;
x.push(temp1);y.push(temp2);deep.push(tempdeep+1);
}
}
return inf;
}
void change(int l,int h)
{
for(int i = 1;i<=h;i++)
num[l][i] = 1;
}
int main()
{
// freopen("code.in","r",stdin);
// freopen("code.out","w",stdout);
std::cin>>n>>k;
for(int i = 1;i<=n;i++)
{
int a;
std::cin>>a;
change(i,a);
}
std::cin>>m;
for(int i = 1;i<=m;i++)
{
int a,b;
std::cin>>a>>b;
indexx[i] = a;indexy[i] = b;
}
int ans = 0;
for(int i = 1;i<=m;i++)
for(int j = i+1;j<=m;j++)
{
memset(f,0,sizeof(f));
if(get_ans(indexx[i],indexy[i],indexx[j],indexy[j])<=k)
{
ans++;
}
}
std::cout<<ans;
// std::cout<<get_ans(3,1,4,3);
// fclose(stdin);
// fclose(stdout);
return 0;
}
随时随刻,当你想要颓废的时候,想想之前为何而来,当你想要放弃的时候,想想之前你为何坐在这里