HDU 6225 Little Boxes
Problem Description
Little boxes on the hillside.
Little boxes made of ticky-tacky.
Little boxes.
Little boxes.
Little boxes all the same.
There are a green boxes, and b pink boxes.
And c blue boxes and d yellow boxes.
And they are all made out of ticky-tacky.
And they all look just the same.
Input
The input has several test cases. The first line contains the integer t (1 ≤ t ≤ 10) which is the total number of test cases.
For each test case, a line contains four non-negative integers a, b, c and d where a, b, c, d ≤ 2^62, indicating the numbers of green boxes, pink boxes, blue boxes and yellow boxes.
Output
For each test case, output a line with the total number of boxes.
Sample Input
4
1 2 3 4
0 0 0 0
1 0 0 0
111 222 333 404
Sample Output
10
0
1
1070
简要题意
n组数, 每组4个数, 求每组这4个数的和
题目分析
大数相加, 四个数的范围都是2^62, 和的最大值为2^64, 而unsigned long long的最大值为2^64-1, 故进行一次2^64的特判即可.
代码
#include<stdio.h>
int main(void)
{
int n;
unsigned long long a, b, c, d;
scanf("%d", &n);
while(n--)
{
scanf("%llu %llu %llu %llu", &a, &b, &c, &d);
if( a==4611686018427387904 && b==4611686018427387904 && c==4611686018427387904 && d==4611686018427387904)
{
printf("18446744073709551616\n");
}
else
{
printf("%llu\n", a+b+c+d);
}
}
return 0;
}
思路二
用一般的大数方法相加完成该题目
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXN 100
char result[MAXN], final[MAXN];
int strfin;
void BigNumberAdd( char* addx, char* addy)
{
int i, j;
int lenx, leny, lensum;
memset(result, 0, sizeof(result));
memset(final, 0, sizeof(final));
lenx = strlen(addx);
leny = strlen(addy);
lensum = lenx > leny ? lenx : leny;
for( i=0; i<lenx; i++) addx[i] -= '0';
for( i=0; i<leny; i++) addy[i] -= '0';
for( j=0; j<lenx && j<leny; j++)
{
result[j] = addx[lenx-j-1] + addy[leny-j-1];
}
if( j<lensum)
{
if( j==lenx)
{
while( j<lensum)
{
result[j] = addy[leny-j-1];
j++;
}
}
else if( j==leny)
{
while( j<lensum)
{
result[j] = addx[lenx-j-1];
j++;
}
}
}
for( i=0; i<lensum; i++)
{
if( result[i]>=10)
{
result[i] %= 10;
result[i+1] ++;
}
}
i = 0;
if( result[lensum] > 0)
{
final[i++] = result[lensum] + '0';
}
for( j=0; j<lensum; j++)
{
final[i++] = result[lensum-j-1] + '0';
}
final[i] = '\0';
strfin = strlen(final);
}
int main(void)
{
char adda[MAXN], addb[MAXN], addc[MAXN], addd[MAXN];
char addab[MAXN], addcd[MAXN];
int t, i;
scanf("%d", &t);
while(t--)
{
scanf("%s %s %s %s", adda, addb, addc, addd);
BigNumberAdd(adda, addb);
for( i=0; i<strfin; i++) addab[i] = final[i];
addab[i] = '\0';
BigNumberAdd(addc, addd);
for( i=0; i<strfin; i++) addcd[i] = final[i];
addcd[i] = '\0';
BigNumberAdd(addab, addcd);
for( i=0; i<strfin; i++)
{
printf("%c", final[i]);
}
printf("\n");
}
return 0;
}
收获与反思
- 大数相加的模板有所熟悉
- 注意初始化(赋值为0)
- 对一个字符串使用strlen()函数时, 可能会因为"0"而出现问题, 此时应"另辟蹊径"
- puts()函数自带"\n"
- 尽量将 循环/判断 语句分行写, 便于调试, 也不易出错
- 尽量将"i++"之类的语句分行写, 理由同上
- unsigned long long的转义符号为%llu, 范围是0~2^64-1