• zzuli2130卡时bfs题


    https://acm.zzuli.edu.cn/zzuliacm/problem.php?id=2130

    2130: hipercijevi

    Time Limit: 1 Sec  Memory Limit: 128 MB
    Submit: 196  Solved: 12

    SubmitStatusWeb Board

    Description

    在遥远的星系, 最快的交通方式是用某种管道。 每个管道直接互相连接N个站。 那么我们从第一个站到第N个站最少要经过多少个站呢?

    Input

    输入文件的第一行为T表示有T组数据

    每个数据第一行包含三个正整数 N (1<=N<=100000) 表示站的个数; K (1<=K<=1000) 表示一个管道直接连接了多少个站; M (1<=M<=1000) 表示管道的数量。

    接下来的M行, 每行包含一个管道的描述: K个正整数, 表示这个管道连接的K个站的编号。

    Output

    输出文件T行,每行包含一个正整数,表示从第一个站到第N个站最少需要经过多少个站。 如果无法从第一个站到达第N个站,输出-1 。

    Sample Input

    2 9 3 5 1 2 3 1 4 5 3 6 7 5 6 7 6 8 9 15 8 4 11 12 8 14 13 6 10 7 1 5 8 12 13 6 2 4 10 15 4 5 9 8 14 12 11 12 14 3 5 6 1 13

    Sample Output

    4 3 
    比赛时想到的是DIJ后来学长说是BFS,XJB>_<写半天MLE接着TLE...当时倒是想到了输入外挂不过没用过以为不会节约多大时间。
    下来后题解也说是BFS,群上说前向星,好久没用过,有人说边数100w时dij 前向星秒杀vector果断试试,结果980ms水过,接着上外挂660>_<

    #include<bits/stdc++.h>
    using namespace std;
    inline int read()
    {
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
    }

    struct node
    {
    int id,s;
    };
    struct Edge
    {
    int next;
    int to;
    int w;
    }edges[2000005];
    int head[200005];
    bool vis[200005];
    int cnt;
    int n;
    void add(int u,int v,int w){
    edges[cnt].w=w;
    edges[cnt].to=v;
    edges[cnt].next=head[u];
    head[u]=cnt++;
    }
    int bfs()
    {
    queue<node> Q;
    node temp,cur;
    vis[1]=1;
    cur.id=1,cur.s=0;
    Q.push(cur);
    while(!Q.empty()){
    cur=Q.front();Q.pop();
    int u=cur.id;
    for(int i=head[u];~i;i=edges[i].next){
    int p=edges[i].to;
    if(vis[p]) continue;
    vis[p]=1;
    temp=cur;
    temp.id=p;
    temp.s++;
    Q.push(temp);
    if(temp.id==n) return temp.s/2+1;
    }
    }
    return -1;
    }
    int main()
    {
    int t,m,i,j,k;
    scanf("%d",&t);
    while(t--){
    int tmp[1005];
    cnt=0;
    //cin>>n>>k>>m;
    scanf("%d%d%d",&n,&k,&m);
    for(i=0;i<=n+m;++i) head[i]=-1,vis[i]=0;
    for(i=1;i<=m;++i){int p=n+i;
    for(j=1;j<=k;++j){
    //scanf("%d",&tmp[j]);
    tmp[j]=read();
    add(tmp[j],p,1);
    add(p,tmp[j],1);

    }
    }

    //cout<<bfs()<<endl;
    printf("%d ",bfs());
    }
    return 0;
    }

  • 相关阅读:
    3.node.js AssertionError: false == true错误解决
    9.获取当前时区时间和utc时间的工具方法
    2.Express封装mysq方法
    1.Express初识
    poj 3617
    前缀和
    pop 反序列化
    Reverse前两个题
    前两个Web题
    Misc
  • 原文地址:https://www.cnblogs.com/zzqc/p/6723555.html
Copyright © 2020-2023  润新知