ZOJ 3583 Simple Path[并查集]

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 ≤ MN(N - 1) / 2), S(0 ≤ S < N), D(0 ≤ D < N). N is the number of vertices, M is the number of edges, S and 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

深搜找不在任意简单路径上出现的点,超时了。

深搜 Code
#include<stdio.h>
#include<string.h>
#define clr(x)memset(x,0,sizeof(x))
#define maxn 105
int s,t,n,m;
int v[maxn];
int find[maxn];
int pre[maxn];
int g[maxn][maxn];
void dfs(int x)
{
int i;
if(x==t||find[x])
{
while(x!=s)
{
find[x]=1;
x=pre[x];
}
return;
}
for(i=0;i<n;i++)
{
if(g[x][i]&&!v[i])
{
v[i]=1;
pre[i]=x;
dfs(i);
v[i]=0;
}
}
}
int main()
{
int i,vv,uu,tot;
while(scanf("%d%d%d%d",&n,&m,&s,&t)!=EOF)
{
clr(find); clr(g); clr(v);
memset(pre,-1,sizeof(pre));
for(i=0;i<m;i++)
{
scanf("%d%d",&vv,&uu);
g[vv][uu]=g[uu][vv]=1;
}
v[s]=1;
dfs(s);
find[s]=find[t]=1;
tot=0;
for(i=0;i<n;i++)
if(!find[i])
tot++;
printf("%d\n",tot);
}
return 0;
}

 并查集 code:

View Code
如果是简单路径上的点,不管去掉哪一个点,都能使改点和s,或 t属于同一个集合,如果不是简单路径上的点,一定能找到一个点删掉以后使它不与s,t属于同一个集合。
#include<stdio.h>
#include<string.h>
#define clr(x)memset(x,0,sizeof(x))
int f[102];
int g[102][102];
int find(int x)
{
int r=x;
while(r!=f[r])
r=f[r];
int i=x,j;
while(i!=r)
{
j=f[i];
f[j]=r;
i=j;
}
return r;
}
void join(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
{
if(fx<fy)
f[fy]=fx;
else f[fx]=fy;
}
}
int main()
{
int p,q,s,t,n,m,i,j,k;
int res[102];
while(scanf("%d%d%d%d",&n,&m,&s,&t)!=EOF)
{
clr(g);
clr(res);
for(i=0;i<m;i++)
{
scanf("%d%d",&p,&q);
g[p][q]=g[q][p]=1;
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
f[j]=j;
for(j=0;j<n;j++)
for(k=j+1;k<n;k++)
{
if(j!=i&&k!=i&&g[j][k])
join(j,k);
}
for(j=0;j<n;j++)
if(j!=i&&find(j)!=find(s)&&find(j)!=find(t))
res[j]=1;
}
int tot=0;
for(i=0;i<n;i++)
if(res[i])
tot++;
printf("%d\n",tot);
}
return 0;
}

 

转载于:https://www.cnblogs.com/dream-wind/archive/2012/03/15/2397865.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值