HDOJ - 1004 - Let the Balloon Rise(字符串)

方法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;
	}
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章