求助,样例过了,但是爆0(按y总的模板写的)
查看原帖
求助,样例过了,但是爆0(按y总的模板写的)
848619
remain11楼主2023/2/21 17:18

按y总的模板写的,单链表 dfs用的小根堆,bfs用的排序加队列

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>

using namespace std;

const int N=1e5+10,M=1e6+10;
int h[N],e[M],ne[M],idx;
int d[N],q[M];
bool st[N];
int n,m,r;

void add(int a,int b){
    e[idx]=b;
    ne[idx]=h[a];
    h[a]=idx++;
}

void dfs(int u){
    st[u]=true;
    printf("%d ",u);
    r++;
    if(r==n){
        return;
    }
    priority_queue<int,vector<int>,greater<int>>heap;
    for(int i=h[u];i!=-1;i=ne[i]){
        int j=e[i];
        if(!st[j]){
            heap.push(j);
        }
    }
    while(!heap.empty()){
        dfs(heap.top());
        heap.pop();
    }
}

void bfs(){
    memset(d,-1,sizeof(d));
    int hh=0,tt=0;
    d[1]=0,q[0]=1;
    while(hh<=tt){
        int p=tt;
        for(int k=hh;k<=p;k++){
            int t=q[hh++];
            printf("%d ",t);
            for(int i=h[t];i!=-1;i=ne[i]){
                int j=e[i];
                if(d[j]==-1){
                    q[++tt]=j;
                    d[j]=d[t]+1;
                }
            }
        }
        sort(q+hh,q+tt+1);
    }
}

int main(){
    scanf("%d%d",&n,&m);
    memset(h,-1,sizeof(h));
    for(int i=1;i<=m;i++){
        int a,b;
        scanf("%d%d",&a,&b);
        add(a,b);
    }
    dfs(1);
    puts("");
    bfs();
    return 0;
} 
2023/2/21 17:18
加载中...