C/C++队列

队列的定义:
queue < int > vis;

队列的常见操作:
1. vis.push(x)
2. vis.pop()
3. vis.empty()
4. vis.front()
5. vis.back()

队列的有关题目
1.http://acm.nefu.edu.cn/problemShow.php?problem_id=1634
这个题的重点在于要设置一个cnt!!!每循环一次加上一,如果是m的倍数的话再进行删除!!!

#include <bits/stdc++.h>
using namespace std;
queue<int>q;
int main()
{
    int n,m,tmp,cnt;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        q.push(i);
    cnt=0;
    while(q.size()>1)
    {
        cnt++;
        tmp=q.front();q.pop();
        if(cnt%m!=0)q.push(tmp);
    }
    printf("%d\n",q.front());
    return 0;
} 

2.http://acm.nefu.edu.cn/problemShow.php?problem_id=1662
这个题的关键在于要设置一个数组a,然后对a[1]进行赋值,然后理解打表的过程从而写出循环!!!

#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int n,p2,p3,a[N];
int main()
{
    ios::sync_with_stdio(false);
    cin>>a[1]>>n;
    p2=1,p3=1;
    for(int i=2;i<=n;i++)
    {
        a[i]=min(2*a[p2]+1,3*a[p3]+1);
        if(a[i]==2*a[p2]+1)p2++;
        if(a[i]==3*a[p3]+1)p3++;
    }
    printf("%d\n",a[n]);
    return 0;
}

3.https://www.luogu.org/problemnew/show/P2058
可以看结题报告中写的代码理一下解题思路,好难好难好难!

#include <bits/stdc++.h>
using namespace std;
struct node
{
    int t,x;//t为时间,x为国籍
};
queue<node>q;
int t,k,n,x,ans,a[300010];
inline int read()//快读,洛谷运行时间从389ms提速到205ms
{
    register int x=0,f=1;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')f=-1; c=getchar();}
    while(c>='0'&&c<='9'){x=(x<<3)+(x<<1)+(c^48);c=getchar();}
    return x*f;
}
int main()
{
    n=read();
    while(n--)
    {
        t=read();k=read();
        while(k--)
        {
            x=read();
            q.push({t,x});
            if(a[x]==0)ans++;
            a[x]++;
        }
        while(t-q.front().t>=86400&&!q.empty())
        {
            node tmp=q.front();q.pop();
            a[tmp.x]--;
            if(a[tmp.x]==0)ans--;
        }
        printf("%d\n",ans);
    }
    return 0;
}

4.http://acm.nefu.edu.cn/problemShow.php?problem_id=1663
利用队列实现搜索的一个简单题目,但是千万要记得入队标记!!!!

#include <bits/stdc++.h>
using namespace std;
const int N=110;
int n,bx,ex,vis[N],a[N][N];
struct node
{
    int x,cnt;//x记录当前搜索到的编号,cnt记录步数
};
queue<node>q;
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>bx>>ex;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
        cin>>a[i][j];
    q.push({bx,0});//先把起点入队,开始时cnt=0
    vis[bx]=1;//入队标记
    while(!q.empty())//开始搜索,用队列实现BFS
    {
        int x=q.front().x;
        int cnt=q.front().cnt;
        q.pop();//按队列顺序依次取出队首,取出后记得要出队
        if(x==ex){printf("%d\n",cnt-1);break;}//找到终点,输出答案,搜索结束
        for(int i=1;i<=n;i++)
        {
            if(a[x][i]&&!vis[i])//找到x能到达的点i
            {
                vis[i]=1;//入队标记
                q.push({i,cnt+1});//入队
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值