跳到正文

个人记录

P1653 [USACO04DEC] Cow Ski Area G 题解

MuseInDay_1095约 5 分钟
原文
文章信息与版本

文章信息

发布
2024年1月9日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 5 分钟
获赞
2

版本

  1. v1当前

P1653 [USACO04DEC] Cow Ski Area G 题解

P1653 题目传送门 难度: 提高+/省选−\blue{提高+/省选−}

Tag: Tarjan, 强连通分块,图论。

非常水的一道题目,即使是我都能写出来(

题目翻译:

奶牛喜欢区域 G

题意简化:

给出一个 WW 列 LL 行的高度矩阵,只能从高度较高的坐标到达相邻的高度较矮或相等的坐标。求至少需要建多少个双向边使得整个矩阵联通。

思路:

其实将每个高度相等的联通块进行建图,然后判断这个图上面有分别有多少个入度出度为 00 的点,分别记为 inin,outout,答案即为 max⁡(in,out)\max(in,out)(因为只要入度出度为 00 的点两两相连,最后就会剩下 max⁡(in,out)−min⁡(in,out)\max(in,out)-\min(in,out) 个单独的入度或出度为 00 的点没有连接,于是再互相连接就好了。所以答案即为 max⁡(in,out)\max(in,out))。

需要注意的一点是,如果最后整个图会形成一个整的联通块的话答案就直接是 00 了,所以要特判一下。(不然会 WA 掉 #3 和 #9)

没有使用Tarjan。

Code:

C++
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<string>
#include<cmath>
#include<vector>
#define ENDL putchar('\n')
using namespace std;
template <class T> void read(T &x);
template <class T> void write(T x);
typedef long long ll;
const int maxn=500+5;

int n,m;
const int d[5]={1,0,-1,0,1};
int a[maxn][maxn];

namespace graph{
	int in[maxn*maxn],out[maxn*maxn];//出度和入度
	void add(int x,int y){
		++in[y],++out[x];
	}
};
using namespace graph;

int tot;
int h[maxn*maxn];//联通块的高度
int color[maxn][maxn];//坐标所在的联通块的颜色
bool vis[maxn][maxn];
void dfs(int x,int y,int colo){
	color[x][y]=colo;//染色
	vis[x][y]=1;
	for(int i=0;i<4;++i){
		int xx=x+d[i],yy=y+d[i+1];
		if(xx>0 and xx<=n and yy>0 and yy<=m and !vis[xx][yy] and a[x][y]==a[xx][yy]){//判断新坐标是否合法
			dfs(xx,yy,colo);
		}
	}
}

int main(){
	read(m),read(n);//反着读
	for(int i=1;i<=n;++i){
		for(int j=1;j<=m;++j){
			read(a[i][j]);
		}
	}
	for(int i=1;i<=n;++i){
		for(int j=1;j<=m;++j){
			if(vis[i][j])continue;
			dfs(i,j,++tot);
			h[tot]=a[i][j];
		}
	}//记录各个联通块
	for(int i=1;i<=n;++i){
		for(int j=1;j<=m;++j){
			int xx,yy,u,v;
			xx=i+1,yy=j;
			u=color[i][j],v=color[xx][yy];
			if(u!=v and xx<=n and yy<=m){
				if(h[u]>h[v])add(u,v);
				else add(v,u);
			}
			xx=i,yy=j+1;
			u=color[i][j],v=color[xx][yy];
			if(u!=v and xx<=n and yy<=m){
				if(h[u]>h[v])add(u,v);
				else add(v,u);
			}
		}
	}//建图,为了避免重复记录只向右和向下两个方向进行建边,并且只需要记录每个点的入度和出度即可
	if(tot==1){
		write(0),ENDL;
		return 0;
	}//特判
	int ansin=0,ansout=0;
	for(int i=1;i<=tot;++i){
		if(in[i]==0)++ansin;
		if(out[i]==0)++ansout;
	}
	write(max(ansin,ansout));//统计答案并输出
	return 0;
}

完结~真的很简单呢。