poj3694 Network

本文探讨了在连通无向图中增加边时割边的变化,并使用Tarjan算法进行求解。通过具体实例分析了如何正确处理重复边的问题,同时分享了优化邻接表实现的经验。

给你一张连通无向图,向图中加Q次边,问你每次加边后,图中有几条割边。是可以有重边的,比如原图中边(1,2)是一条割边,再加一条边(1,2) ,就消除掉了一条割边。

但是这个题有点别扭,加边的时候会有重边,一开始建图的时候也会有重边,但是建图时不考虑重边(去重)也能AC,比如

3 4
1 2
2 3
1 2
2 3
2
1 2
2 3
这组数据,结果感觉应该是0 0,但是用tarjan+lca的程序结果应该都是1 0,也都AC了。

还有就是用vector建邻接表,写着简单,但是时间效率并不高。用typedef vector<int>ve; vector<ve>head(maxn);代替//vector<int>head[maxn]; 效率会高一点。vector< typeName > vec(n); 表示vec中含有n个值为0的元素;

感觉要考虑重边其实用tarjan算法办不了啊。此外tajan中还有一个小细节,就是在 if(!vis[v]){ }内标记割边,可以达到去重边的效果,而不用预先去重边。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<queue>
#include<vector>
#include<set>
#define LL long long
#define clean(a) memset(a,0,sizeof(a))
#define maxn 110000

using namespace std;
//vector<int>head[maxn];
typedef vector<int>ve;
vector<ve>head(maxn);
int dep_tmp;
int dfn[maxn],low[maxn],dep[maxn],pre[maxn];
bool vis[maxn],cut[maxn];
int num;
void tarjan_dfs(int rt,int father)
{
	dfn[rt]=low[rt]=dep_tmp++;
	dep[rt]=dep[father]+1;
	vis[rt]=true;
	for(int i=0,len=head[rt].size();i<len;++i)
	{
		int v=head[rt][i];
		if(!vis[v])
		{
			pre[v]=rt;
			tarjan_dfs(v,rt);
			low[rt]=min(low[rt],low[v]);
			if(low[v]>dfn[rt])
			{
					cut[v]=true;
					num++;
			}
		}
		else if(v!=father)
			low[rt]=min(low[rt],dfn[v]);
//		if(low[v]>dfn[rt])//如果有重边结果会错(偏大)
//		{
//				cut[v]=true;
//				num++;
//		}
//		if( (rt!=root && low[v]>=dfn[rt])  ||  (rt==root && son>1))//割点
	}
}
void add(int x,int y)
{
	while(dep[x]<dep[y])
	{
		if(cut[y]) cut[y]=false,num--;
		y=pre[y];
	}
	while(dep[x]>dep[y])
	{
		if(cut[x])  cut[x]=false,num--;
		x=pre[x];
	}
	while(x!=y)
	{
		if(cut[x]) cut[x]=false,num--;
		if(cut[y]) cut[y]=false,num--;
		x=pre[x],y=pre[y];
	}
}
void ini(int n)
{
	for(int i=0;i<=n;++i)	head[i].clear(),pre[i]=i;
	clean(dfn);
	clean(low);
	clean(vis);
	clean(pre);
	clean(dep);
	clean(cut);
	dep_tmp=1;
}
int main()
{
	int n,m,I=0;
	while(scanf("%d%d",&n,&m),n!=0 || m!=0)
	{
		ini(n);
		for(int i=0;i<m;++i)
		{
			int x,y;
			scanf("%d%d",&x,&y);
			head[x].push_back(y);
			head[y].push_back(x);
		}
		dep[1]=0;
		num=0;
		tarjan_dfs(1,1);
		int m;
		scanf("%d",&m);
		printf("Case %d:\n",++I);
		for(int i=0;i<m;++i)
		{
			int x,y;
			scanf("%d%d",&x,&y);
			add(x,y);
			printf("%d\n",num);
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值