【JZOJ3896】战争游戏【割点】

版权声明:若希望转载,在评论里直接说明即可,谢谢! https://blog.csdn.net/SSL_ZYC/article/details/86650946

题目大意:

在这里插入图片描述


思路:

很明显的,对于经过每个割点的路径,有两种情况讨论:

  1. 由外部连进来的:用外部的节点总个数 × \times 缩点中节点的总个数
  2. 两个缩点自己相连:用两个缩点的节点个数相乘,最后因为会多算一倍,所以 ÷ 2 \div 2

T a r j a n Tarjan 加上简单的树上计算就可以过。


代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N=50010;
const int M=100010;
int n,m,x,y,num,tot,head[N],size[N],dfn[N],low[N],ans[N];
bool vis[N];

struct edge
{
	int next,to;
}e[M*2];

void add(int from,int to)
{
	e[++tot].to=to;
	e[tot].next=head[from];
	head[from]=tot;
}

void tarjan(int x,int fa)  //割点
{
	size[x]=1;
	dfn[x]=low[x]=++num;
	int sum=0,s=0;
	for (int i=head[x];~i;i=e[i].next)
	{
		int y=e[i].to;
		vis[y]=0;
		if (!dfn[y])  //没有走到过
		{
			tarjan(y,x);
			vis[y]=1;
			size[x]+=size[y];
			if(dfn[x]<=low[y]) sum+=size[y];
		}
		if (y!=fa)
			low[x]=min(low[x],low[y]);
	}
	for (int i=head[x];~i;i=e[i].next)  //求答案
	{
		int y=e[i].to;
		if (dfn[x]<=low[y]&&vis[y])
		{
			s+=(sum-size[y])*size[y];
			ans[x]+=(n-sum-1)*size[y];
		}
	}
	ans[x]+=s/2;
}

int main()
{
	memset(head,-1,sizeof(head));
	scanf("%d%d",&n,&m);
	for (int i=1;i<=m;i++)
	{
		scanf("%d%d",&x,&y);
		add(x,y);
		add(y,x);
	}
	tarjan(1,0);
	for (int i=1;i<=n;i++)
		printf("%d\n",ans[i]+n-1);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/SSL_ZYC/article/details/86650946