【洛谷P3505】TELTeleportation

题目

题目链接:https://www.luogu.com.cn/problem/P3505
给一张图,要求你再尽可能的多连边,使得从\(1\)\(2\)至少要经过\(5\)条边。

思路

考虑怎样才能使1到2的路径中正好有5条边。那么肯定是\(1\to p\to x\to y\to q\to 2\),其中\(p\)\(1\)相邻,\(q\)\(2\)相邻。
把所有点分为\(5\)个集合,分别为与1相邻的点,与2相邻的点,与1距离为2的点,与2距离为2的点,其他点。
那么\(x\)就是与1距离2的点,\(y\)就是与2距离为2的点。
\(cnt1,cnt2\)分别为与1相邻的点,与2相邻的点,\(cnt3,cnt4\)分别为与1距离为2的点,与2距离为2的点。
那么肯定与1相邻的点两两相连,与2相邻的点两两相连,不直接与1或2相邻的点两两相连是最优的。
先不看“其他点”,那么答案就是上述点两两相连的路径+\(cnt1\times cnt3+cnt2\times cnt4\)
那么我们考虑把“其他点”划进“与1距离为2的点”,“与2距离为2的点”中。显然,划进更大的集合是更优的。
所以就求出每一个集合的大小,然后求出每一个集合内两两相连的边数和相邻集合的边数,然后减去边数集合。
时间复杂度\(O(n+m)\)

代码

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

const int N=40010,M=2000010;
int n,m,tot,cnt1,cnt2,ans,pos[N],cnt[6],head[N];

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

int read()
{
	int d=0; char ch=getchar();
	while (!isdigit(ch)) ch=getchar();
	while (isdigit(ch)) d=(d<<3)+(d<<1)+ch-48,ch=getchar();
	return d;
}

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

int main()
{
	memset(head,-1,sizeof(head));
	n=read(); m=read();
	for (int i=1,x,y;i<=m;i++)
	{
		x=read(); y=read();
		add(x,y); add(y,x);
		if (x==1) pos[y]=1;
		if (y==1) pos[x]=1;
		if (x==2) pos[y]=2;
		if (y==2) pos[x]=2;
	}
	for (int i=1;i<=n;i++)
		if (pos[i]==1 || pos[i]==2)
			for (int j=head[i];~j;j=e[j].next)
				if (e[j].to>2 && !pos[e[j].to]) pos[e[j].to]=pos[i]+2;
	for (int i=3;i<=n;i++)
		if (pos[i]) cnt[pos[i]]++;
	cnt[5]=n-cnt[1]-cnt[2]-2;
	ans=cnt[1]*(cnt[1]-1)/2+cnt[2]*(cnt[2]-1)/2+cnt[5]*(cnt[5]-1)/2;
	ans+=cnt[1]+cnt[2]+cnt[3]*cnt[1]+cnt[4]*cnt[2]+(cnt[5]-cnt[3]-cnt[4])*max(cnt[1],cnt[2]);
	printf("%d",ans-m);
	return 0;
}
原文地址:https://www.cnblogs.com/stoorz/p/12182770.html