zoukankan      html  css  js  c++  java
  • 牛客网练习赛7-D-无向图(bfs,链式前向星)

    题意:中文题;

    思路:就是找某个点距离其他点的距离,他给你很多点也无所谓。用一个dist【】数组,这个数组保存的是他给你的点到其他点的最短距离且标记的作用,然后bfs搜索就行了。

    代码:

    #include<iostream>
    #include<algorithm>
    #include<cstring>
    #include<cstdio>
    #include<cmath>
    #include<cstdlib>
    #include<set>
    #include<map>
    #include<queue>
    #include<vector>
    #define ll long long int
    #define mod 1000000007
    #define me(a,b) memset(a,b,sizeof(a))
    const int inf=0x7fffffff;
    const int maxn=10010;
    using namespace std;
    int head[maxn];
    int cnt;
    int dist[maxn];
    struct node
    {
    int to;
    int next;
    }edge[maxn];
    void add(int u,int v)
    {
    edge[cnt].to=v;
    edge[cnt].next=head[u];
    head[u]=cnt++;
    }
    int main()
    {
    int s,t,n,m,q,x;
    int u,v;
    int ans;
    me(head,-1);
    cnt=0;
    queue<int>qu;
    scanf("%d%d%d",&n,&m,&q);
    for(int i=1;i<=m;i++)
    {
    scanf("%d%d",&u,&v);
    add(u,v);
    add(v,u);
    }
    while(q--)
    {
    scanf("%d%d",&t,&s);
    me(dist,-1);ans=0;
    while(t--)
    scanf("%d",&x),dist[x]=0,qu.push(x);//将所有给你的点都存进一个数组;
    while(!qu.empty())
    {
    int z=qu.front();
    qu.pop();
    for(int i=head[z];i!=-1;i=edge[i].next)//假设某个点距离第一个点距离为2,那么第一次for到不了这个点,如果第二个点距离这个点为1,第二次for确定距离;
    {
    if(dist[edge[i].to]==-1)
    dist[edge[i].to]=dist[z]+1,qu.push(edge[i].to);
    }
    }
    for(int i=1;i<=n;i++)
    {
    if(dist[i]!=-1&&dist[i]<=s)
    ans++;
    }
    printf("%d ",ans);
    }
    return 0;
    }

  • 相关阅读:
    ubuntu下常用的apt-get 命令参数
    探索equals()和hashCode()方法
    Java多线程编程核心技术
    线程的状态
    详解Java中的clone方法
    为什么String类是不可变的?
    深入理解final和static关键字
    彻底理解ThreadLocal
    反射消除String类对象的不可变特性
    进程和线程
  • 原文地址:https://www.cnblogs.com/huangdao/p/7954835.html
Copyright © 2011-2022 走看看