Abridged problem statement
Given a set of strings output the string with the highest number of distinct characters. In case two strings have the same number of characters, output the lexicographically smallest one.
Problem Statement
Constraints
1 ≤ T ≤ 100
1 ≤ N ≤ 100
Approach
Initialize an integer to max to 0 and string leader to empty string for every test case.
For every name initialize char_arr to 0.
For every character in the name if char_arr[index of character] equals 0 then increment char_arr[index of character] and count. At the end of the iteration count holds the number of distinct characters in the name.
If count is greater than max, then update max to count and leader to the current name.
if count equals max, then update leader to lexicographically smallest of leader and current name.
Code
#include <iostream> #include <vector> #include <cstring> #include <fstream> using namespace std; inline int GetPosition(char c) { return c - 'A' + 1;} string breakTie(string name1, string name2){ if(name1<name2) return name1; else return name2; } int main(){ freopen("A-large-practice.in", "r", stdin); freopen("outputlarge.txt", "w", stdout); int t, n, count, max; int char_arr[27]; string name, leader; cin>>t; for(int i=1; i<=t; i++){ max = 0; cin>>n; leader = ""; for(int j=0; j<n+1; j++){ getline(cin, name); //getline reads in a newline character in first iteration if(j==0) continue; count = 0; memset(char_arr, 0, sizeof char_arr); for(int k=0; k<name.length(); k++){ if(name[k]==' ') continue; int x = GetPosition(name[k]); if(char_arr[x] == 0) { count++; char_arr[x]++; } } if(count > max){ max = count; leader = name; } else if(count == max){ leader = breakTie(leader, name); } } cout<<"Case #"<<i<<": "<<leader<<endl; } return 0; }
Comments
Post a Comment