E - Avoid Knight Attack Editorial by blueberry1001

実装テクニックについて

解法は公式解説と同じです。

\(8\) 通りの移動先について、以下のように実装することで実装量を軽くすることができます。(例としてC++とPythonによる実装を記載していますが、他の言語でも同様に書くことができると思います。)

このように、「少し数字は違うがほとんど同じ処理」は、今回のようにforeach文を使ったり関数化したりすることで実装量を軽くすることができるので、覚えておくとよいでしょう。

#include<bits/stdc++.h>
using namespace std;
int main(){
	int n,m;cin >> n >> m;
	set<pair<int,int>>s;
	for(;m--;){
	  int a,b;cin >> a >> b;
		s.insert({a,b});
		for(int i:{-1,1}){
			for(int j:{-2,2}){
				s.insert({a+i,b+j});
				s.insert({a+j,b+i});
			}
		}
	}
	long long ans = n;
	ans *= n;
	for(auto[x,y]:s){
		if(1<=x&&1<=y&&x<=n&&y<=n)ans--;
	}
	cout << ans << endl;
	return 0;
}

提出コード(C++)

n,m = map(int,input().split())
s = set()
for _ in range(m):
  a,b = map(int,input().split())
  s.add((a,b))
  for i in [-1,1]:
    for j in [-2,2]:
      s.add((a+i,b+j))
      s.add((a+j,b+i))
ans = n*n
for i,j in s:
  if 1<=i<=n and 1<=j<=n:
    ans-=1
print(ans)

提出コード(Python)

posted:
last update: