bzoj 4997: [Usaco2017 Feb]Why Did the Cow Cross the Road III(Pu1 2018.10.1)

博客介绍了如何使用深度优先搜索(DFS)解决USACO2017二月比赛中的题目,该题涉及到连通块的计算。文章讨论了如何搜索每个连通块并计算每块内的牛的数量,然后将这些数量相乘得到答案。作者对Luogu题解中MLE(内存限制超时)的代码能AC(接受)表示疑惑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法:dfs,连通块

难度:NOIP

题解:搜索出每个连通块,找到每个连通块里有几头牛。然后每个连通块内牛数量相乘,求和即为正解

不清楚luogu题解中的代码明明MLE了,却还能AC???

代码如下:

时间复杂度:O(n^2)

#include <cstdio>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>
#include <cmath>
#include <algorithm>
#define ll long long
#define N 35005
using namespace std;
int viss[105][105];
int cow[105][105];
struct node
{
	int x,y;
}cc[10005];
int n,k,r,col=1;
int usles;
bool edg[105][105][105][105];
void dfs(int x,int y)
{
	if(x+1<=n)
	{
		if(!viss[x+1][y])
		{
			if(edg[x][y][x+1][y]||edg[x+1][y][x][y])
			{
				usles=4;
			}else
			{
				viss[x+1][y]=col;
				dfs(x+1,y);
			}
		}
	}
	if(x-1>0)
	{
		if(!viss[x-1][y])
		{
			if(edg[x][y][x-1][y]||edg[x-1][y][x][y])
			{
				usles=4;
			}else
			{
				viss[x-1][y]=col;
				dfs(x-1,y);
			}
		}
	}
	if(y+1<=n)
	{
		if(!viss[x][y+1])
		{
			if(edg[x][y][x][y+1]||edg[x][y+1][x][y])
			{
				usles=4;
			}else
			{
				viss[x][y+1]=col;
				dfs(x,y+1);
			}
		} 
	}
	if(y-1>0)
	{
		if(!viss[x][y-1])
		{
			if(edg[x][y][x][y-1]||edg[x][y-1][x][y])
			{
				usles=4;
			}else
			{
				viss[x][y-1]=col;
				dfs(x,y-1);
			}
		} 
	}
}
int kk[10005];
int main()
{
	//126 MB
	//printf("%d\n",(sizeof(kk)+sizeof(edg)+sizeof(cc)+sizeof(cow)+sizeof(viss))/1024/1024);
	scanf("%d%d%d",&n,&k,&r);
	int tt=0; 
	for(int i = 1;i <= r;i++)
	{
		int a,b,x,y;
		scanf("%d%d%d%d",&a,&b,&x,&y);
		edg[a][b][x][y]=1;
		edg[x][y][a][b]=1;
	}
	int tto=0;
	for(int i = 1;i <= k;i++)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		cow[a][b]=1;
		cc[++tto].x=a;
		cc[tto].y=b;
	}
	for(int i = 1;i <= k;i++)
	{
		if(!viss[cc[i].x][cc[i].y])
		{
			viss[cc[i].x][cc[i].y]=col; 
			dfs(cc[i].x,cc[i].y);
			col++;
		}
	}
	for(int i = 1;i <= n;i++)
	{
		for(int j = 1;j <= n;j++)
		{
			if(cow[i][j]) kk[viss[i][j]]++;
		}
	}
	int ans=0;
	for(int i = 1;i < col;i++)
	{
		for(int j = i+1;j < col;j++)
		{
			ans+=kk[i]*kk[j];
		}
	}
	printf("%d\n",ans); 
	return 0 ;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值