水题 HDU-1004 Let the Balloon Rise
题目链接:杭电1004
题目大意:找出出现次数最多的颜色
解题思路:将数据储存在结构体里 最后找到次数最多的 记得每进行一次进行初始化
2019.09.21更新:使用map集合 颜色为key 次数为value
这题学到了map可以使用[]直接进行操作 与Java不同
代码块:
#include<iostream>
#include<cstring>
using namespace std;
struct col {
char color[16];
int sum = 0;
}c[1009];
char sss[16] = { '\0' };
int main() {
int n;
while (cin >> n) {
if (n == 0) return 0;
int index = 0;
int max = 0;
for (int i = 0; i < n; i++) {
cin >> sss;
int j;
for (j = 0; j < index; j++) {
if (strcmp(sss, c[j].color) == 0) {
c[j].sum++;
}
}
if (j == index) {
strcpy(c[index].color, sss);
c[index].sum++;
index++;
}
memset(sss, '\0', sizeof(sss));
}
for (int i = 0; i < index; i++) {
if (c[i].sum > max) {
max = c[i].sum;
}
}
for (int i = 0; i < index; i++) {
if (c[i].sum == max) {
cout << c[i].color << endl;
break;
}
}
memset(c, 0, sizeof(c));
}
return 0;
}
代码块
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
map<string, int> ma;
map<string, int>::iterator it;
while(cin>>n){
if(n == 0)break;
string str;
for(int i=0; i<n; i++){
cin>>str;
ma[str]++;
}
int maxValue = 0;
for(it = ma.begin(); it != ma.end(); it++){
if(it->second > maxValue){
maxValue = it->second;
str = it->first;
}
}
cout<<str<<endl;
ma.clear();
}
return 0;
}