Sunday, October 16, 2011

[UVa] 10862 - Connect the Cable Wires

I found a nice way to treat C Structures as same (almost) as C++ Classes, having functions for their operations. While solving this problem I implemented that.

Method:
Analyze the problem with cases 1, 2, 3, 4 and if needed, 5. You'll soon find out that it's about even positioned Fibonacci numbers.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char res[1000000];
typedef struct bNum
{
    int size;
    char val[2000];
} BigNum;

void setNum(char *val, BigNum *pThis)
{
    strcpy(pThis->val,val);
    pThis->size=strlen(val);
}
char *getNum(BigNum *pThis)
{
    return pThis->val;
}
int addNum(BigNum *p1, BigNum *p2, BigNum *p3)
{
    int i, j, k, car=0, cur;

    for (i=p1->size-1, j=p2->size-1, k=0 ; i>=0 || j>=0 ; i--, j--, k++)
    {
        cur = (i>=0?p1->val[i]:'0') + (j>=0?p2->val[j]:'0') + car - 96;
        if (cur>9)
        {
            car=1;
            res[k]=(cur-10)+'0';
        } else
        {
            car=0;
            res[k]=cur+'0';
        }
    }
    if (car)
    {
        res[k++]='1';
    }
    p3->size=k;
    for (--k, i=0 ; k>=0 ; k--, i++)
    {
        p3->val[i]=res[k];
    }
    p3->val[i]='\0';
}

BigNum fibs[5000];

int main()
{
    int i, n;
    setNum("1",&fibs[1]);
    setNum("1",&fibs[2]);

    for (i=3 ; i<=4001 ; i++)
    {
        addNum(&fibs[i-1],&fibs[i-2],&fibs[i]);
    }

    while (scanf("%d",&n) && n)
    {
        printf("%s\n",getNum(&fibs[2*n]));
    }
    return 0;
}

No comments:

Post a Comment

Post your comment here. If you want to say something about programming problems, scripts, software etc, please try to be as descriptive as possible.

Connect Rapoo MT750S with Linux (Tested on Manjaro)

 I bought this obvious copy of MX Master 2S in hopes of having the device switching functionality along with a lightweight body because I ha...