1. 程式人生 > 其它 >20201218大一集訓題j題國際象棋chess

20201218大一集訓題j題國際象棋chess

技術標籤:c++cC語言

題目:
Given an m x n chessboard where you want to place chess knights. You have to find the number of maximum knights that can be placed in the chessboard such that no two knights attack each other.

Those who are not familiar with chess knights, note that a chess knight can attack 8 positions in the board as shown in the picture below.

Input
Input starts with an integer T (≤ 41000), denoting the number of test cases.

Each case contains two integers m, n (1 ≤ m, n ≤ 200). Here m and n corresponds to the number of rows and the number of columns of the board respectively.

Output
For each case, print the case number and maximum number of knights that can be placed in the board considering the above restrictions.

Sample Input
3

8 8

3 7

4 10

Sample Output
Case 1: 32

Case 2: 11

Case 3: 20
翻譯:
給你一個n x m的棋盤,你可以在上面放置騎士棋子。
你必須找到棋盤上可以放置的最大棋子數,這樣沒有兩個騎士互相攻擊。
規則如下;
在這裡插入圖片描述

ps:騎士。白點代表可以攻擊的地方。
輸入:
t代表輸入的陣列,有t個。
n,m代表輸入棋盤的行列數。
輸出:
巴拉巴拉
。。。。。。。。。。。
我的思路:
看到給的資料就想到找規律,發現輸出的都是n*m/2的數,不是整數就加1
原始碼:

#include<stdio.h>
#include<math.h>
int main() { int n; scanf("%d",&n); int copy=n; while(n--){ int a,b; scanf("%d%d",&a,&b); int t=ceil(a*b/2.0); printf("Case %d: %d\n",copy-n,t); } return 0; }

結果錯了,發現沒有討論特殊情況。
正確思路:
當n或m為1時,可以放m或n個;
當n貨m等於2時,又可以找到一種規律:
第一行: O O X X O O X X O O X X [ ] [ ]
第二行: O O X X O O X X O O X X [ ] [ ];
也就是可以找到如上週期型的規律,週期為4;
換句話說,當列數為4的週期時可以,就為列數;
當不等於時就要分情況:
如果取餘小於2,就n/44+2(n/42);
如果大於等於2,就n/4
4+4;
就這樣;
然後其他的情況都是以我的思路去算。
正確程式碼:

#include<cstdio>
#include<math.h>
#include<iostream>
using namespace std;
int main()
{
	int n;
	scanf("%d",&n);
	int copy=n;
	while(n--){
		int a,b,sum,_;
		scanf("%d%d",&a,&b);
		sum=a*b;
		if(a==1||b==1) _=sum;
		else if(a==2||b==2){
			if(a==2) swap(a,b);
			if(a%4<2) _=a/4*4+(a%4)*2;
			else if(b%4>=2) _=a/4*4+4; 
		} 
		else{
			_=ceil(a*b/2.0);
		}
		printf("Case %d: %d\n",copy-n,_);
	}
	return 0;
}

反思:
swap函式的理解與運用。

嗯,->o<(做題自閉後的我)

拓展:
找規律,加分情況的題。