professorbrill's blog

By professorbrill, 11 years ago, translation, In English
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#define MX 1000005
using namespace std;

struct BN
{
    int siz, num[MX];
    BN()
    {
        siz = 1;
        memset(num, 0, sizeof(num));
    }
    BN(string &a)
    {
        siz = a.size();
        memset(num, 0, sizeof(num));
        for (int i = 0; i < a.size(); i++)
            num[i] = a[a.size() - i - 1] - '0';
    }
    void len()
    {
        siz = MX - 1;
        while (siz > 0 && num[siz] == 0)
            siz--;
        siz++;
    }
    void inc()
    {
        num[0]++;
        for (int i = 0; i < MX - 1; i++)
        {
            num[i + 1] += num[i] / 10;
            num[i] %= 10;
        }
        len();
    }
    string tostring()
    {
        string a;
        for (int i = siz - 1; i >= 0; i--)
            a += (char)(num[i] + '0');
        return a;
    }
};

BN w;
string s, t, u, v, v1;

string sol()
{
    if (s.size() % 2 == 1)
    {
        u = s.substr(0, s.size() / 2 + 1);
        v = u;
        reverse(v.begin(), v.end());
        v = u + v.substr(1);
        if (v <= s)
        {
            w = BN(u);
            w.inc();
            u = w.tostring();
            v = u;
            reverse(v.begin(), v.end());
            v = u + v.substr(1);
        }
        u = s.substr(0, s.size() / 2);
        v1 = u;
        reverse(v1.begin(), v1.end());
        v1 = u + s[s.size() / 2] + v1;
        if (v1 <= s)
        {
            w = BN(u);
            w.inc();
            u = w.tostring();
            v1 = u;
            reverse(v1.begin(), v1.end());
            v1 = u + s[s.size() / 2] + v1;
        }
        if (v < v1)
            return v;
        return v1;
    }
    u = s.substr(0, s.size() / 2);
    v = u;
    reverse(v.begin(), v.end());
    v = u + v;
    if (v <= s)
    {
        w = BN(u);
        w.inc();
        u = w.tostring();
        v = u;
        reverse(v.begin(), v.end());
        v = u + v;
    }
    return v;
}

int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> s;
        t = sol();
        cout << t << "\n";
    }
}

Actually I do have a solution for this problem (maybe it is not correct but I didn't create a post for helping with solution). But I wonder why each time I call sol(), the program crashes and gives SIGSEGV.

Can anyone explain?

P.S. BN is a big number structure. Used it to increase a big number by one.

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
11 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I have got AC on this solution. Read it. It may help you.