牛客网暑期ACM多校训练营(第二场) I.car (找规律)

题目链接

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

White Cloud has a square of n*n from (1,1) to (n,n).
White Rabbit wants to put in several cars. Each car will start moving at the same time and move from one side of one row or one line to the other. All cars have the same speed. If two cars arrive at the same time and the same position in a grid or meet in a straight line, both cars will be damaged.
White Cloud will destroy the square m times. In each step White Cloud will destroy one grid of the square(It will break all m grids before cars start).Any car will break when it enters a damaged grid.

White Rabbit wants to know the maximum number of cars that can be put into to ensure that there is a way that allows all cars to perform their entire journey without damage.

(update: all cars should start at the edge of the square and go towards another side, cars which start at the corner can choose either of the two directions)

For example, in a 5*5 square

legal

illegal(These two cars will collide at (4,4))

illegal (One car will go into a damaged grid)

输入描述:

The first line of input contains two integers n and m(n <= 100000,m <= 100000)
For the next m lines,each line contains two integers x,y(1 <= x,y <= n), denoting the grid which is damaged by White Cloud.

输出描述:

Print a number,denoting the maximum number of cars White Rabbit can put into.

示例1

输入

2 0

输出

4

备注:

 
 

题意:给出一个n阶方正,上面有m个坑,随后是m行,每行一个x,y表示该位置存在一个坑,现在问你最多能在该方正格子中最多放置多少量车,使得这些车开始行驶后不会发生相撞或者掉坑(当一辆车遇到边界就停下来了,且车的行驶速度都是每秒一格),还要求车只能安排在边界,并且行驶方向面向于该边界平行的边界.

题解:对于没有坑的题从题目2*2的图可以发现最优的情况就是上图所摆放的方式,那么对于下一个偶数情况4*4,我们同样可以如此

那么,可以发现对于没有坑的情况N为偶数时最多可以为2*N,同理,对于N为奇书即是在偶数最中间插入了一行一列,那么在这行这列中,我们只能选取任意一个放置一辆车,因此总结出没有坑的情况下:ans=2*N - (N mod 2) ;

       那么现在讨论下出现坑的时候,对于N为偶数很简单,只需要使用row和col数组记录下某行或某列存在坑,那么这行或列的车自然不能放置了,就是ans--即可.

       对于N为奇数的情况,我们无非就是要考虑下最中间那行和列的情况,因为其他的结果都和偶数的时候一样处理即可,对于最中间那行和列,存在3中情况: 

        情况一:这行和列都不存在坑,那么结果不变,就是2*N-1;

        情况二:这行或列存在一个有坑,可是我们在和偶数一样处理的时候会ans-=1,都是实际我们只需要选择没有坑的那条路放置车即可,因此答案不变还是2*N-1,所以我们需要ans++;

        情况三:这行且列都存在坑,那么我们不可能在此放置车,可是我们在和偶数一样处理的时候会ans-=2,我们需要ans++,表示该中间行和列都不存在放置车辆的情况.

         综合以上得到:当N为奇数的时候,若是行或列存在坑都需要ans++即可.

代码如下:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<vector>
using namespace std;
#define ll long long
const int maxn = 1e5 + 10;
int row[maxn], col[maxn];
int main() {
	int n, m, x, y, ans;
	scanf("%d%d", &n, &m);
	while (m--) {
		scanf("%d%d", &x, &y);
		row[x] = 1;
		col[y] = 1;
	}
	if (n % 2) ans = 2 * n - 1;
	else ans = 2 * n;
	for (int i = 1; i <= n; i++) {
		if (row[i] > 0) ans--;
		if (col[i] > 0) ans--;
	}
	if (n % 2 && (row[n / 2 + 1] || col[n / 2 + 1]))
		ans++;
	printf("%d\n", ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41156591/article/details/81150959