HDU 1228 A + B 字符串操作(常规 & hash)

7 篇文章 0 订阅
3 篇文章 0 订阅
<pre name="code" class="cpp">#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <map>
using namespace std;

char ary[11][10]={"zero","one","two","three","four","five","six","seven","eight","nine","ten"};

void main()
{
	int i,a,b,j,k,sum;
	string s1,s2;
	
	map<string,int> mp;
	for(i = 0;i< 11;i++)
		mp[ary[i]] = i;

	while(1)
	{
		sum = 0;
		while(cin>>s1,s1 != "+")
		{
			sum = sum*10 + mp[s1];
		}
		a = sum;
		
		sum = 0;
		while(cin>>s2,s2 != "=")
		{
			sum = sum*10 + mp[s2];
		}
		b = sum;
		
	    if(a == 0 && b == 0)
			break;
	    cout<<a+b<<endl;
	}
	
}	

 
#include <stdio.h>  //代码二
#include <string.h>

char week[10][10]={"zero","one","two","three","four","five","six","seven","eight","nine"}; //二维,一维就超过了字节

int sear(char num[])
{
   int i;
   for (i=0;i<=9;i++)
   {
	   if(!strcmp(num,week[i]))
		   break;
   }
   return i;
}

int main()           //字符串的存入不包括空格
{
	int i,a,b;
	char num[10];
	while (1)
	{
		a=0;
		while (scanf("%s",num) && strcmp(num,"+"))
		{
			a=a*10+sear(num);
		}
		b=0;
		while (scanf("%s",num) && strcmp(num,"="))
		{
			b=b*10+sear(num);
		}
		if(a==0 && b==0) return 0;
		else
		printf("%d\n",a+b);
	}

	return 0;
}

hash做法

#include <stdio.h>
#include <string.h>
#define  max 10000  


char week[10][10]={"zero","one","two","three","four","five","six","seven","eight","nine"}; //二维,一维就超过了字节
int hash[15];

// BKDR Hash Function
unsigned int BHash(char* str)
{
    unsigned int seed = 31 ; // 31 131 1313 13131 131313 etc..
    unsigned int hash = 0 ;
    while (*str)
    {
        hash = hash*seed + (*str ++ );
    }
    return (hash & 0x7FFFFFFF );
}

int main()           //字符串的存入不包括空格
{
	int i,a,b,k;
	char num[10];
	for (i=0;i<10;i++)
	{
		k=BHash(week[i])%max;   //max要大,不然会冲突
		hash[k]=i;
	}
	while (1)
	{
		a=0;
		while (scanf("%s",num) && strcmp(num,"+"))
		{
            k=BHash(num)%max;
			a=a*10+hash[k];
		}
		b=0;
		while (scanf("%s",num) && strcmp(num,"="))
		{
			k=BHash(num)%max;
			b=b*10+hash[k];
		}
		if(a==0 && b==0) return 0;
		else
			printf("%d\n",a+b);
	}
	
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值