[One question a day] No two

Source of the topic
Niuke.com
Link: No two

Title description
Erhuo Xiaoyi has a W*H grid box, the row number of the grid is 0~H-1, and the column number of the grid is 0~W-1. At most one cake can be placed in each grid, and the Euclidean distance between any two cakes cannot be equal to 2. For two grid coordinates (x1, y1), the Euclidean distance of (x2, y2) is: ((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2)) Arithmetic square root, Xiao Yi wants to know how many cakes can be put in the grid box at most.

Enter a description:

Each array contains the grid length and width W, H, separated by spaces. (1 ≤ W, H ≤ 1000)

Output description:

Output the maximum number of cakes you can put

enter:

3 2

Output:

4

The
key point in solving the problem : ((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2)) The square root of the arithmetic is equal to 2 and the cake cannot be put. Here the condition becomes: ( (x1-x2) * (x1-x2) + (y1-y2) * (y1-y2)) == 4 Can not put cake, equal to 4 in the following situations:
1+3=4
3+1=4
2 +2=4
0+4=4
4+0=4
Obviously, the first 3 are impossible, because (x1-x2) * (x1-x2) or (y1-y2) * (y1-y2) is impossible Equal to 2 or 3, either equal to 0 or equal to 4.

Draw a conclusion: satisfy the condition x1 == x2, y1-y2 == 2 or x1-x2 == 2, y1 == y2.

Code display

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    
    
	int w, h, res = 0;
	cin >> w >> h;
	vector<vector<int>> a;
	a.resize(w);
	for(auto& e : a)
		e.resize(h, 1);
	for(int i = 0;i < w;i++)
	{
    
    
		for(int j = 0;j < h;j++)
		{
    
    
			if(a[i][j] == 1)
			{
    
    
				res++;
				if((i + 2) < w)
					a[i + 2][j] = 0;
				if((j + 2) < h)
					a[i][j + 2] = 0;
			}
		}
	}
	cout << res << endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/zhao_leilei/article/details/110424030