方法1:边输入边查找,存在次数加1,不存在插入这个颜色。
AC代码
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
#include <algorithm>
#include <cmath>
#include <ctime>
using namespace std;
const int maxn = 1000+10;
struct Ballon
{
char color[20];
int t;
};
Ballon ballon[maxn];
int n = 0, m = 0;
void Search(char s[])
{
int i = 0;
for (i = 0; i < m; i++)
{
if (!strcmp(s, ballon[i].color))
{
ballon[i].t++;
return;
}
}
strcpy(ballon[m].color, s);
ballon[m].t = 1;
m++;
return ;
}
int main()
{
#ifdef Local
freopen("a.in", "r", stdin);
#endif
int i = 0;
while (cin >> n && n)
{
memset(ballon, '\0', sizeof(ballon[0]));
m = 0;
int max = 0, num = 0;
while (n--)
{
char s[20];
cin >> s;
Search(s);
}
for (i = 0; i < m; i++)
{
if (ballon[i].t > max)
{
max = ballon[i].t, num = i;
}
}
cout << ballon[num].color << endl;
}
return 0;
}
方法2:快排后找出现次数最多的。
(未通过的)
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
#include <algorithm>
#include <cmath>
#include <ctime>
using namespace std;
char ballon[1000][20];
int cmp (const void *a, const void *b)
{
return *(char *)a - *(char *)b;
}
int main()
{
#ifdef Local
freopen("a.in", "r", stdin);
#endif
int n = 0, i = 0;
while (cin >> n && n)
{
char ans[20];
int count = 1, max = 0;
memset(ballon, '\0', sizeof(ballon[0]));
for (i = 0; i < n; i++)
cin >> ballon[i];
qsort(ballon, n, sizeof(ballon[0]), cmp);
for (i = 0; i < n; i++)
{
if (!strcmp(ballon[i], ballon[i+1]))
count++;
else
{
if (count > max)
{
max = count;
strcpy(ans, ballon[i]);
}
count = 1;
}
}
cout << ans << endl;
}
}