Official

C - Almost Equal Editorial by en_translator


In this problem, it is sufficient to inspect all possible \(N!\) permutations to check if each satisfy the conditions spending \(\mathrm{O}(NM)\) time, and print Yes them if any of them does and No otherwise.

The problem is how to implement it. In C++, there is a function like next_permutation. If you provide it with a sorted vector, it enumerates all possible permutations obtainable by rearranging the array.

Most languages have a function like this, so it is sufficient to implement using this function.

Sample code (C++)

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n,m;
  cin>>n>>m;
  vector<string> s(n);
  for(int i=0;i<n;i++) cin>>s[i];
  sort(s.begin(),s.end());
  do{
    bool ok=true;
    for(int i=0;i<n-1;i++){
      int cnt=0;
      for(int j=0;j<m;j++) if(s[i][j]!=s[i+1][j]) cnt++;
      if(cnt!=1) ok=false;
    }
    if(ok){
      cout<<"Yes"<<endl;
      return 0;
    }
  }while(next_permutation(s.begin(),s.end()));
  cout<<"No"<<endl;
}

posted:
last update: