有没有大佬用邻接矩阵写的QAQ
查看原帖
有没有大佬用邻接矩阵写的QAQ
1002517
Adorable_楼主2024/10/15 19:08

rt,为什么这个dfs排序后输出的顺序不对呀qwq

#include<bits/stdc++.h>
using namespace std;

#define int long long
const int N = 1e5+5,M = 1e6+5;
int head[N],n,m,cnt;
bool f1[N],f2[N];
struct Edge
{
	int u,v;
	bool operator<(const Edge& cmp) const
	{
		if(u == cmp.u) return v<cmp.v;
    	return u<cmp.u;
    }
}E[M];
struct edge{int nxt,to;}e[M];
void add(int u,int v)
{
	e[++cnt].nxt = head[u];
	e[cnt].to = v;
	head[u] = cnt;
}
void dfs(int x)
{
	if(f1[x]) return;
	printf("%lld ",x);
	f1[x] = 1;
	for(int i = head[x];i;i = e[i].nxt)
	{
		dfs(i);
	}
}

signed main()
{
	scanf("%lld%lld",&n,&m);
	for(int i = 1;i<=m;i++) scanf("%lld%lld",&E[i].u,&E[i].v);
	sort(E+1,E+m+1);
	for(int i = 1;i<=m;i++) add(E[i].u,E[i].v);
	dfs(1);
//	bfs(1);
	printf("\n");
	return 0;
}


2024/10/15 19:08
加载中...