CSES - Datatähti 2025 alku - Results
Submission details
Task:Niitty
Sender:maweiyin24562
Submission time:2024-10-31 11:57:15 +0200
Language:Pascal
Status:COMPILE ERROR

Code

program Solution;

const
  N = 509;
  F = 26;

var
  n, C, ans: longint;
  pre: array[0..N, 0..N, 0..F] of longint;
  compact: array[0..N, 0..F] of longint;
  idx: array[0..F] of longint;

function IC(c: char): longint;
begin
  IC := Ord(c) - Ord('A');
end;

function sum(x1, y1, x2, y2, id: longint): longint;
begin
  sum := pre[x2, y2, id] - pre[x1-1, y2, id] - pre[x2, y1-1, id] + pre[x1-1, y1-1, id];
end;

function check(x1, y1, x2, y2: longint): boolean;
var
  id: longint;
begin
  check := true;
  for id := 1 to C do
    if sum(x1, y1, x2, y2, id) = 0 then
    begin
      check := false;
      exit;
    end;
end;

function cpc_sum(l, r, id: longint): longint;
begin
  cpc_sum := compact[r, id] - compact[l-1, id];
end;

function cpc_check(l, r: longint): boolean;
var
  id: longint;
begin
  cpc_check := true;
  for id := 1 to C do
    if cpc_sum(l, r, id) = 0 then
    begin
      cpc_check := false;
      exit;
    end;
end;

var
  i, j, k, id: longint;
  c: char;
  top, btm, l, r: longint;

begin
  readln(n);
  C := 0;
  ans := 0;

  // Initialize arrays
  fillchar(pre, sizeof(pre), 0);
  fillchar(compact, sizeof(compact), 0);
  fillchar(idx, sizeof(idx), 0);

  for i := 1 to n do
    for j := 1 to n do
    begin
      read(c);
      id := IC(c);
      if idx[id] = 0 then
      begin
        inc(C);
        idx[id] := C;
      end;

      for k := 1 to C do
        if k = idx[id] then
          pre[i, j, k] := pre[i-1, j, k] + pre[i, j-1, k] - pre[i-1, j-1, k] + 1
        else
          pre[i, j, k] := pre[i-1, j, k] + pre[i, j-1, k] - pre[i-1, j-1, k];
    end;

  // Main processing
  for top := 1 to n do
    for btm := top to n do
    begin
      if not check(top, 1, btm, n) then
        continue;

      for j := 1 to n do
        for id := 1 to C do
          compact[j, id] := sum(top, 1, btm, j, id);

      l := 1;
      r := 1;

      while r <= n do
      begin
        while (l < r) and cpc_check(l+1, r) do
          inc(l);

        if cpc_check(l, r) then
          ans := ans + l;

        inc(r);
      end;
    end;

  writeln(ans);
end.