zoj3583(并查集)

Simple Path

Time Limit: 2 Seconds       Memory Limit: 65536 KB

A path with no repeated vertices of an undirected graph is called a simple path. Given an undirected graph and two verteices S and D, return the number of vertics which don't lie on any simple paths between S and D.

Input

The input contains multiple test cases.

Each case starts with a line of four integers, N(1 < N ≤ 100), M(1 ≤ M ≤ N(N - 1) / 2), S(0 ≤ S < N), D(0 ≤ D < N). N is the number of vertices, M is the number of edges, Sand D are two different vertices. Then M lines follow, each line contains two different integers A(0 ≤ A < N) and B(0 ≤ B < N), which represents an edge of the graph. It's ensure that there is at least one simple path between S and D.

Output

Output the number of such vertics, one line per case.

Sample Input
4 3 0 2
0 1
1 2
1 3
4 4 0 2
0 1
1 2
1 3
2 3
Sample Output
1
0

题意:找到不属于s到d的任何一条简单路中的点的个数(简单路:不重复走同一个点)

思路:好题!一开始真想不到可以用并查集做。考虑不全想用入度出度做,其实不行。如果一个点i不是s到d的任何一条简单路上的点,则必然可以删除一个点使得这个点i不再与s和d连通,这样把所有点都枚举删除一遍,找出所有因此不再与s和d相连的点的个数就可以。也可以用dfs。


#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#define MAX_V 105
int n,m,s,d;
bool map[MAX_V][MAX_V];
int par[MAX_V];
int rank[MAX_V];
bool flag[MAX_V];
void init(int n)
{
	for(int i=0;i<n;i++)
	{
		par[i]=i;
		rank[i]=0;
	}
}
int find(int x)
{
	if(par[x]==x)
		return x;
	else
		return par[x]=find(par[x]);
}
void unite(int x,int y)
{
	x=find(x);
	y=find(y);
	if(x==y)return;
	if(rank[x]==rank[y])
		par[x]=y;
	else
	{
		par[y]=x;
		if(rank[x]==rank[y])rank[x]++;
	}
}
int main()
{
	int x,y;
	while(~scanf("%d%d%d%d",&n,&m,&s,&d))
	{
		memset(flag,0,sizeof(flag));
		memset(map,0,sizeof(map));
		for(int i=0;i<m;i++)
		{
			scanf("%d%d",&x,&y);
			map[x][y]=1;
			map[y][x]=1;
		}
		for(int i=0;i<n;i++)            //枚举点 
		{
			init(n);
			for(int j=0;j<n-1;j++)
			{
				for(int k=j+1;k<n;k++)
				{
					if(j!=i&&k!=i&&map[j][k])         //合并操作,把i孤立,相当于删除i 
					{
						unite(j,k);
					}
				}
			}
			for(int j=0;j<n;j++)        //如果这个点不与s和d相连就是所要找的点 
			{
				if(j!=i&&find(j)!=find(s)&&find(j)!=find(d))flag[j]=1;
			}
		}
		int ans=0;
		for(int i=0;i<n;i++)
		{
			if(flag[i])ans++;
		}
		printf("%d\n",ans);
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值