Official

D - Counting Ls Editorial by en_translator


Let us take an arbitrary triple as an example.

......o
.......
.o....o

By the conditions “exactly two of them are in the same row” and “exactly two of them are in the same column,” it follows that exactly one of them satisfies both. In the example above, the bottom-right o does.

Now let us fix (exhaustively enumerate) this square \(s\). How can we choose the other two squares?

It turns out that we choose:

  • one o in the same row as \(s\), except for \(s\); and
  • one o in the same column as \(s\), except for \(s\).

The number of choices can be found as (the number of o in the same row as \(s\) except for \(s\)) \(\times\) (the number of o in the same column as \(s\) except for \(s\)).

This can be computed fast by counting o squares in each row and column.

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  int n;
  cin >> n;
  vector<string> s(n);
  vector<long long> bi(n,0),bj(n,0);
  for(int i=0;i<n;i++){
    cin >> s[i];
    for(int j=0;j<n;j++){
      if(s[i][j]=='o'){
        bi[i]++;
        bj[j]++;
      }
    }
  }

  long long res=0;
  for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
      if(s[i][j]=='o'){
        res+=(bi[i]-1)*(bj[j]-1);
      }
    }
  }
  cout << res << "\n";
  return 0;
}

posted:
last update: