usako_lynn usako_lynn - 1 month ago 7
C++ Question

Google code jam 2017 Round A APAC Country Leader

My first question on StackOverFlow.

This is the question: https://code.google.com/codejam/contest/11274486/dashboard#s=p0

I finished my c++ code and it worked normally, outputting file correctly (I think). But Dashboard system responded incorrectly. I don't know why it happened.

I hope somebody can figure out what's wrong with my algorithm, or share your code if you solved it. Thanks!!

And sorry for my poor English.

This is my code with Xcode 7.3.1:

// already solved the problem and removed my bad code :P





Thanks to Hagen von Eitzen,

Here is the right version:

#include <iostream>
using namespace std;

int letternum(string name)
{
int i,num = 0;
int count[26];
for (i=0; i<26; i++)
count[i] = 0;
for (i=0; i<name.length(); i++)
{
if (name[i] != ' ')
count[name[i]-'A'] = 1;
}
for (i=0; i<26; i++)
{
num += count[i];
}
return num;
}

int main()
{
int T,N,t,n;
int longlen,namelen;
char tempchar[21];
string longest;
string name;

FILE *fin = fopen("A-large-practice.in", "r");
FILE *fout = fopen("A-large-practice.out", "w");

fscanf(fin, "%d", &T);

for (t=0; t<T; t++)
{
memset(tempchar, '\0', 21);
longest = "";
name = "";
fscanf(fin, "%d\n", &N);
fscanf(fin, "%[^\n]%*c", tempchar);
longest = tempchar;
longlen = letternum(longest);

for (n=1; n<N; n++)
{
memset(tempchar, '\0', 21);
name = "";
fscanf(fin, "%[^\n]%*c", tempchar);
name = tempchar;
namelen = letternum(name);
if (longlen == namelen )
{
if (longest > name)
{
longest = name;
longlen = letternum(longest);
}
}
if ( longlen < namelen )
{
longest = name;
longlen = letternum(longest);
}
}
fprintf(fout, "Case #%d: %s\n", t+1, longest.c_str());
}
}

Answer

Names may consist of up to 20 characters. You need to reserve space for the terminating NUL character as well. Otherwise, your code may crash if the input really is 20 chars long

letternum: Performance (hardly relevant here): You always count to the maximal length 20, which may be unnecessarily long; also, you are just lucky that you did not forget to zero the full array. If you replace the ++ with a =1 in the first loop, you need only sum in the second loop.

Also, why don't you use standards such as string or strcmp?