图创建遍历
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N =20010,M=20010;
int h[N],e[M],ne[M],w[M],idx;
int n,m,k;
bool st[N];
void add(int a,int b){
//if(a>b)swap(a,b);
e[idx]=b;
int i=0;int t=0;
for(i=h[a];i!=-1;i=ne[i]){
if(e[i]>b)break;
t=i;
}
if(i==h[a]){ ne[idx]=h[a]; h[a]=idx++;}
else{ne[idx]=ne[t]; ne[t]=idx++;}
}
void dfs(int u){
cout<<u<<" ";
st[u]=true;
for(int i=h[u];i!=-1;i=ne[i]){
int j=e[i];
if(!st[j])dfs(j);
}
}
int main(){
cin>>n>>m;
memset(h,-1,sizeof h);
while(m--){
int a,b,c;
cin>>a>>b;
add(a,b);
}
for(int i=0;i<n;i++){
if(!st[i])dfs(i);
}
return 0;
}
拓扑排序 最小
#include<iostream>
#include<queue>
using namespace std;
const int N =110;
int n,m,d[N],h[N],e[M],ne[M],idx,ans[N],id;
bool topsort(){
priority_queue<int,vector<int>,greater<int>>q;q.push(i);
for(int i=0;i<n;i++)if(!d[i])q.push(i);
while(q.size()){
int t=q.front();
q.pop();
ans[id++]=t;
for(int i=h[t];i!=-1;i=ne[i]){
int j=e[i];
if(--d[j]==0)q.push(j);
}
}
return id==n;
}
int main(){
cin>>n>>m;
memset(h,-1,sizeof h);
while(m--){
int a,b;
cin>>a>>b;
add(a,b);
d[b]++;
}
if(!topsort())puts("unworkable project");
else for(int i=0;i<id;i++)cout<<ans[i]<<" ";
return 0;
}
bfs模板
//15
//1012
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
#define x first
#define y second
typedef pair<int,int>PII;
const int N =110;
int n,m,sx,sy,ex,ey,d[N][N],g[N][N];
queue<PII>q;
//PII q[N*N];
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
void inital(){
memset(g,0,sizeof g);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++){
scanf("%d",&g[i][j]);
if(g[i][j]==3){sx=i;sy=j;}
else if(g[i][j]==4){ex=i;ey=j;}
}
}
int bfs(int sx,int sy){
while(!q.empty())q.pop();
q.push({sx,sy});
memset(d,-1,sizeof d);
d[sx][sy]=0;
while(q.size()){
auto t=q.front();
q.pop();
for(int i=0;i<4;i++){
int x=t.x+dx[i],y=t.y+dy[i];
if(x<0||x>=n||y<0||y>=m||g[x][y]==1||d[x][y]!=-1)continue;
d[x][y]=d[t.x][t.y]+1;
q.push({x,y});
}
}
return d[ex][ey];
}
int main(){
while(cin>>n>>m){
inital();
if(bfs(sx,sy)==-1)puts("unreachable");
else cout<<bfs(sx,sy)<<endl;
}
return 0;
}