【华为编程大赛】投票问题

输入若干候选人,以及投票,格式如下,输出(按输入候选人输入顺序)候选人以及得票,以及
无效票数。
Input:
addCandidate xx1
addCandidate xx2
addCandidate xx3
addCandidate xx4
addCandidate xx5
addCandidate xx6
vote xx2
vote xx2
vote xx3
vote xx3
vote xx4
vote xx6
vote xx7
vote xx1
vote xx1
Output:
xx1 2
xx2 2
xx3 2
xx4 1
xx6 1

1

用链表做的,查找不高效,因为要保持输入顺序。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <sstream>
#include <set>
#include <map>
#include <cmath>

using namespace std;
typedef struct person{
	string name;
	int num;
	person *next;
	person(string name, int num)
	{
		this->name = name;
		this->num = num;
		this->next = NULL;
	}
}person;

void destroyList(person *head)
{
	//delete the person node's memory here.
	return;
}

int main()
{
	string lines;
	string word;
	string name;
	person *head = NULL;
	person *tail = NULL;
	while(getline(cin, lines))
	{
		istringstream iss(lines);
		iss>>word;
		iss>>name;
		if (word != "add")
		{
			break;
		}
		
		person * cur = new person(name,0);
		if (head == NULL)
		{
			head = cur;
			tail = cur;
		}
		else 
		{
			tail->next = cur;
			tail = cur;
		}
	}

	int illegal = 0;

	person *tmp = head;
	while(tmp != NULL)
	{
		if (tmp->name == name)
		{
			tmp->num++;
			break;
		}
		else tmp = tmp->next;
	}
	while(getline(cin, lines))
	{
		istringstream iss(lines);
		iss>>word;
		iss>>name;
		if (word == "vote")
		{
			tmp = head;
			while(tmp != NULL)
			{
				if (tmp->name == name)
				{
					tmp->num++;
					break;
				}
				else tmp = tmp->next;
			}
			if (tmp == NULL)
			{
				illegal++;
			}
		}
	}

	tmp = head;
	while(tmp != NULL)
	{
		if (tmp->num > 0)
		{
			cout<<tmp->name<<" "<<tmp->num<<endl;
		}
		tmp = tmp->next;
	}
	cout<<illegal<<endl;
	destroyList(head);

	system("pause");
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值