图论(1)

图论

(一)图的存储与遍历

方法一:直接存边

方法二:邻接矩阵

用bool类型二维数组存储 \(u 是否能到 v\)

方法三:邻接表

P5318为例。

#include <bits/stdc++.h>
#define LL long long
#define ls (p<<1)
#define rs (p<<1|1)
#define INF INT_MAX
#define lowbit(x) (x&-x)
#define mod 1000000007
#define ULL unsigned long long
void write(LL x){
	if(x<0) putchar('-'),x=-x;
	if(x>9) write(x/10);
	putchar(x%10+48);
}
LL read(){
	LL 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<<3)+(x<<1)+ch-48;ch=getchar();}
	return x*f;
}
using namespace std;
const int N=1e5+5;
int n,m,ans[N];
bool vis[N];
vector<int> edge[N*10];
void dfs(int x){
	vis[x]=1;
	printf("%d ",x);
	for(int y:edge[x]){
		if(vis[y]) continue;
		dfs(y);
	}
}
queue<int> q;
void bfs(int s){
	q.push(s);
	vis[s]=1;
	while(!q.empty()){
		int x=q.front();
		q.pop();
		printf("%d ",x);
		for(int y:edge[x]){
			if(vis[y]) continue;
			q.push(y),vis[y]=1;
		}
	}
}
int main(){
#ifdef LOCAL
	freopen("in.in","r",stdin);
	freopen("ans.out","w",stdout);
#endif
	n=read(),m=read();
	int x,y;
	while(m--){
		x=read(),y=read();
		edge[x].push_back(y);
	}
	for(int i=1;i<=n;++i){
		sort(edge[i].begin(),edge[i].end());
	}
	dfs(1);
	puts("");
	memset(vis,0,sizeof(vis));
	bfs(1);
	return 0;
}

方法四:链式前向星

P3916为例。

#include <bits/stdc++.h>
#define LL long long
#define ls (p<<1)
#define rs (p<<1|1)
#define INF INT_MAX
#define lowbit(x) (x&-x)
#define mod 1000000007
#define ULL unsigned long long
void write(LL x){
	if(x<0) putchar('-'),x=-x;
	if(x>9) write(x/10);
	putchar(x%10+48);
}
LL read(){
	LL 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<<3)+(x<<1)+ch-48;ch=getchar();}
	return x*f;
}
using namespace std;
const int N=1e5+5;
int n,m,tot,hd[N],ans[N];
struct node{
	int nxt,to;
}edge[N];
void add_edge(int u,int v){
	edge[++tot]={hd[u],v};
	hd[u]=tot;
}
void dfs(int x){
	for(int i=hd[x];i;i=edge[i].nxt){
		int y=edge[i].to;
		if(ans[y]) continue;
		ans[y]=ans[x];
		dfs(y);
	}
}
int main(){
#ifdef LOCAL
	freopen("in.in","r",stdin);
	freopen("ans.out","w",stdout);
#endif
	n=read(),m=read();
	int x,y;
	while(m--){
		x=read(),y=read();
		add_edge(y,x);
	}
	for(int i=n;i>=1;--i){
		if(ans[i]) continue;
		ans[i]=i;
		dfs(i);
	}
	for(int i=1;i<=n;++i){
		printf("%d ",ans[i]);
	}
	return 0;
}
posted @ 2024-07-02 17:46  mj666  阅读(5)  评论(0编辑  收藏  举报