算法:dfs,连通块
难度:NOIP
题解:搜索出每个连通块,找到每个连通块里有几头牛。然后每个连通块内牛数量相乘,求和即为正解
不清楚luogu题解中的代码明明MLE了,却还能AC???
代码如下:
时间复杂度:
#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 ;
}