Graph Connectivity_图可达_2018_3_3

本文介绍了一种算法,用于维护图中顶点之间的连通性,并能够在插入或删除边后快速查询两个顶点是否连通。算法适用于无向图,能够处理成千上万条指令,包括边的插入、删除及连通性查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Let us consider an undirected graph G = < V, E >. At first there is no edge in the graph. You are to write a program to calculate the connectivity of two different vertices. Your program should maintain the functions inserting or deleting an edge.
Input
The first line of the input contains an integer numbers N (2 <= N <= 1000) -- the number of vertices in G. The second line contains the number of commands Q (1 <= Q <= 20000). Then the following Q lines describe each command, and there are three kinds of commands:

I u v: Insert an edge (u, v). And we guarantee that there is no edge between nodes u and v, when you face this command.
D u v: Delete an existed edge (u, v). And we guarantee that there is an edge between nodes u and v, when you face this command.
Q u v: A querying command to ask the connectivity between nodes u and v.

You should notice that the nodes are numbered from 1 to N.
Output
Output one line for each querying command. Print "Y" if two vertices are connected or print "N" otherwise.
Sample Input
3 
7
Q 1 2
I 1 2
I 2 3
Q 1 3
D 1 2
Q 1 3
Q 1 1
Sample Output
N
Y
N
Y
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const int N=1005;
const int M=2e4+5;

bool h[N][N],v[N];

struct AA{
	int y,nex;
}g[M*2];
int sz,head[N];
void insert(int x,int y){
	g[++sz].y=y;
	g[sz].nex=head[x];
	head[x]=sz;
}

void dfs(int x){
	v[x]=1;
	for(int i=head[x];i;i=g[i].nex){
		int y=g[i].y;
		if(v[y]||!h[x][y])continue;
		dfs(y);
	}
}

int main(){
	int n,q;
	scanf("%d%d",&n,&q);
	int x,y;
	char c;
	sz=0;
	memset(h,0,sizeof(h));
	memset(head,0,sizeof(head));
	while(q--){
		scanf(" %c %d%d",&c,&x,&y);
		if(c=='Q'){
			memset(v,0,sizeof(v));
			dfs(x);
			if(v[y])puts("Y");
			else puts("N");
		}else if(c=='I'){
			h[x][y]=h[y][x]=1;
			insert(x,y);insert(y,x); 
		}else{
			h[x][y]=h[y][x]=0;
		}
	}
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值