結果

問題 No.1028 闇討ち
コンテスト
ユーザー fura
提出日時 2020-05-12 05:58:42
言語 C++17
(gcc 15.2.0 + boost 1.89.0)
コンパイル:
g++-15 -O2 -lm -std=c++17 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 97 ms / 2,000 ms
コード長 718 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 1,254 ms
コンパイル使用メモリ 213,864 KB
実行使用メモリ 12,544 KB
最終ジャッジ日時 2026-06-10 02:46:05
合計ジャッジ時間 4,370 ms
ジャッジサーバーID
(参考情報)
judge2_1 / judge3_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 20
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <bits/stdc++.h>

#define rep(i,n) for(int i=0;i<(n);i++)

using namespace std;

const int INF=1<<29;

int main(){
	int n; scanf("%d",&n);
	vector<pair<int,int>> P[1000];
	rep(i,n) rep(j,n) {
		int a; scanf("%d",&a); a--;
		P[a].emplace_back(i,j);
	}

	auto calc=[&](int a,int i){
		int cost=0;
		for(const auto& p:P[a]) cost+=max(abs(p.first-i),p.second);
		return cost;
	};

	int ans=0;
	rep(a,n){
		int lo=0,hi=n;
		while(hi-lo>2){
			int mi1=(2*lo+hi)/3;
			int mi2=(lo+2*hi)/3;

			int cost1=calc(a,mi1);
			int cost2=calc(a,mi2);
			if(cost1<=cost2) hi=mi2;
			else             lo=mi1;
		}
		int res=INF;
		for(int i=lo;i<hi;i++) res=min(res,calc(a,i));
		ans+=res;
	}
	printf("%d\n",ans);

	return 0;
}
0