当前位置: 首页 > 工具软件 > Conquests > 使用案例 >

uva - 10420 - List of Conquests

白星渊
2023-12-01
//#define Local
#include <iostream>
#include <cstring>
#include <stdio.h> 
using namespace std;

#define MAX 100

struct country
{
	char name[MAX];
	int len;
};

void GetCountry (char sub[], char s[])
{
	int i = 0;
	while (s[i] != ' ')
	{
		sub[i] = s[i];
		i++;
	}
	sub[i] = '\0';
}

int SearchAndInsert (country (con[]), char sub[], int *count_country)
{
	int i = 0, flag = 0, j = 0;
	for (i = 0; i < *count_country; i++)
	{
		if (strcmp(sub, (con[i]).name) == 0)	//国家名存在
		{
			(con[i]).len++;
			flag = 1;
		}
	}
	if (0 == flag)	//不存在,插入
	{
		if (*count_country == 0)
		{
			strcpy((con[0]).name, sub);
			(con[0]).len++;
			(*count_country)++;
			return 0;
		}
		for (i = 0; i < *count_country; i++)
		{
			if (strcmp(sub, (con[0]).name) < 0)	//比第一国家靠前
			{
				for(j = *count_country -1; j >= 0; j--)
				{
					strcpy((con[j+1]).name, (con[j]).name); 
					con[j+1].len = con[j].len;
				}
				strcpy((con[0]).name, sub);
				(con[0]).len = 1;
				(*count_country)++;
				return 0;
			}
			else if (strcmp(sub, (con[*count_country - 1]).name) > 0)
			{
				strcpy((con[*count_country]).name, sub);
				(con[*count_country]).len++;
				(*count_country)++;
				return 0;
			}
			else if ((strcmp(sub, (con[i]).name) > 0) && (strcmp(sub, (con[i+1]).name) < 0))
			{
				for(j = *count_country -1; j >= i+1; j--)
				{
					strcpy((con[j+1]).name, (con[j]).name);
					con[j+1].len = con[j].len;
				}
				strcpy((con[i+1]).name, sub);
				(con[i+1]).len = 1;
				(*count_country)++;
				return 0;
			}
		}
	}
}


int main()
{
#ifdef Local
	freopen("a.in", "r", stdin);
	freopen("a.out", "w", stdout);
#endif
	int n = 0, i = 0, count_country = 0;
	char s[MAX], sub[MAX];
	country con[2000] = {"\0", 0};
	cin >> n;
	getchar();
	for (i = 1; i <= n; i++)	//总循环次数
	{
		gets(s);
		GetCountry(sub, s);//取得国家名字
		SearchAndInsert(con, sub, &count_country);//查找并且排序插入。
	}
	for (i = 0; i < count_country; i++)
		cout << con[i].name << ' ' << con[i].len << endl;
}

/*
问题主要是在字符串的排序,思路是对的也认为比较简单就是麻烦些,但是细节问题和多,
例如说移动字符串的时候没有移动长度,没有考虑第一次插入的时候*count_country为0进不去循环,
循环插入了以后还接着循环等等,还要了练习啊!
*/



 类似资料:

相关阅读

相关文章

相关问答