uva - 10420 - List of Conquests

//#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进不去循环,
循环插入了以后还接着循环等等,还要了练习啊!
*/



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值