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

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


你可能感兴趣的:(HDU 1228 A + B 字符串操作(常规 & hash))