Official

C - Just K Editorial by en_translator


There are \(2^K\) ways to choose some of the \(N\) characters.

For each of these ways, find the maximum number of distinct “lowercase English letter that appears in exactly \(K\) of the chosen strings.”

The time complexity is \(\mathrm{O}(2^N \times N \times σ)\), where \(σ\) is the number of letters in lowercase English alphabet.

When implementing, the technique called “bitwise bruteforcing” is useful, where each subset of \(N\) letters is considered as a \(N\)-digit binary integer between \(0\) and \(2^N-1\) (inclusive).

Sample code

#include <bits/stdc++.h>
using namespace std;

int main() {
  int n,k;
  cin>>n>>k;
  vector<string> s(n);
  for(int i=0;i<n;i++) cin>>s[i];
  int ans=0;
  for(int i=0;i<(1<<n);i++){
    vector<int> sum(26);
    for(int j=0;j<n;j++){
      if((i>>j)&1){
        for(int x=0;x<s[j].size();x++) sum[s[j][x]-'a']++;
      }
    }
    int now=0;
    for(int j=0;j<26;j++) if(sum[j]==k) now++;
    ans=max(ans,now);
  }
  cout<<ans<<endl;
}

posted:
last update: