Official

C - RANDOM Editorial by en_translator


This problem can be solved with the following two steps:

A. Simplify the given input
B. Determine if we can sort the columns of \(S\) to make it equal \(T\)

For A., it is a good idea to transpose the rows and columns of \(S\) to convert it to an array of “strings that represent each row;” same apples to \(T\).

A transpose is, given a two-dimensional array \(A\), an operation of constructing \(B\) such that \(B[i][j]=A[j][i]\) in order to swap rows and columns. For more details, please refer to the implementation.

Let us denote the transposed \(S\) and \(T\) by \(^tS\) and \(^tT\), then we can rephrase the problem to solve in B. as well; now we need to determine if we can obtain \(^tT\) by rearranging the rows of \(^tS\) (in other words, you are asked to compare two arrays of strings and determine if you can obtain one by rearranging the other).
Now how can we solve this problem?

In general, the simplest ways to determine if we can rearrange \(P\) to make it equal \(Q\) is to sort both \(P\) and \(Q\) and check if they result in the same sequence (if so, it is possible; otherwise it is impossible).

Indeed, we can solve this problem by sorting the rows of \(^tS\) and \(^tT\) and determine if it yields the same result.

The time complexity of this solution is \(O(HW \log W)\). (The bottleneck is sorting the elements of \(W\), in which a comparison costs \(O(H)\) time.)

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  int h,w;
  cin >> h >> w;
  vector<string> s(h),t(h);
  for(auto &nx : s){cin >> nx;}
  for(auto &nx : t){cin >> nx;}

  // A.
  vector<string> Ts(w),Tt(w);
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      Ts[j].push_back(s[i][j]);
      Tt[j].push_back(t[i][j]);
    }
  }

  // B.
  sort(Ts.begin(),Ts.end());
  sort(Tt.begin(),Tt.end());

  if(Ts==Tt){cout << "Yes\n";}
  else{cout << "No\n";}
  return 0;
}

posted:
last update: