My code gets a TLE (time limit exceeded) on an online judge even though I have coded according to the editorial

Saket Mehta

This is the question link - QSET - Codechef

This is the editorial link - QSET - Editorial

Basically the question queries for the number of substring in some range [L, R]. I have implemented a segment tree to solve this question. I have closely followed the editorial.

I have created a struct to represent a node of the segment tree.

Can someone explain to me how to make this program faster? I'm guessing faster I/O is the key here. Is that so?

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#define ll long long
using namespace std;

struct stnode
{
    ll ans; // the answer for this interval
    ll pre[3]; // pre[i] denotes number of prefixes of interval which modulo 3 give i
    ll suf[3]; // suf[i] denotes number of suffixes of interval which modulo 3 give i
    ll total; // sum of interval modulo 3

    void setLeaf(int value)
    {
        if (value % 3 == 0) ans = 1;
        else ans = 0;
        pre[0] = pre[1] = pre[2] = 0;
        suf[0] = suf[1] = suf[2] = 0;
        pre[value % 3] = 1;
        suf[value % 3] = 1;
        total = value % 3;
    }

    void merge(stnode leftChild, stnode rightChild)
    {
        ans = leftChild.ans + rightChild.ans;
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                if ((i + j) % 3 == 0) ans += leftChild.suf[i] * rightChild.pre[j];

        pre[0] = pre[1] = pre[2] = 0;
        suf[0] = suf[1] = suf[2] = 0;
        for (int i = 0; i < 3; i++)
        {
            pre[i] += leftChild.pre[i] + rightChild.pre[(3 - leftChild.total + i) % 3];
            suf[i] += rightChild.suf[i] + leftChild.suf[(3 - rightChild.total + i) % 3];
        }

        total = (leftChild.total + rightChild.total) % 3;
    }
} segtree[400005];

void buildST(string digits, int si, int ss, int se)
{
    if (ss == se)
    {
        segtree[si].setLeaf(digits[ss] - '0');
        return;
    }
    long left = 2 * si + 1, right = 2 * si + 2, mid = (ss + se) / 2;
    buildST(digits, left, ss, mid);
    buildST(digits, right, mid + 1, se);
    segtree[si].merge(segtree[left], segtree[right]);
}

stnode getValue(int qs, int qe, int si, int ss, int se)
{
    if (qs == ss && se == qe)
        return segtree[si];

    stnode temp;
    int mid = (ss + se) / 2;
    if (qs > mid)
        temp = getValue(qs, qe, 2 * si + 2, mid + 1, se);
    else if (qe <= mid)
        temp = getValue(qs, qe, 2 * si + 1, ss, mid);
    else
    {
        stnode temp1, temp2;
        temp1 = getValue(qs, mid, 2 * si + 1, ss, mid);
        temp2 = getValue(mid + 1, qe, 2 * si + 2, mid + 1, se);
        temp.merge(temp1, temp2);
    }
    return temp;
}

void updateTree(int si, int ss, int se, int index, int new_value)
{
    if (ss == se)
    {
        segtree[si].setLeaf(new_value);
        return;
    }

    int mid = (ss + se) / 2;
    if (index <= mid)
        updateTree(2 * si + 1, ss, mid, index, new_value);
    else
        updateTree(2 * si + 2, mid + 1, se, index, new_value);

    segtree[si].merge(segtree[2 * si + 1], segtree[2 * si + 2]);
}

int main()
{
    ios_base::sync_with_stdio(false);
    int n, m; cin >> n >> m;
    string digits; cin >> digits;
    buildST(digits, 0, 0, n - 1);
    while (m--)
    {
        int q; cin >> q;
        if (q == 1)
        {
            int x; int y; cin >> x >> y;
            updateTree(0, 0, n - 1, x - 1, y);
        }
        else
        {
            int c, d; cin >> c >> d;
            cout << getValue(c-1, d-1, 0, 0, n - 1).ans << '\n';
        }
    }
}

I am getting TLE for larger test cases, ie subtasks 3 and 4 (check the problem page). For subtasks 1 and 2, it gets accepted.

[www.codechef.com/viewsolution/5909107] is an accepted solution. It has pretty much the same code structure except that scanf is used instead of cin. But, I turned off the sync_with_stdio so that shouldn't be a differentiator, right?

Saket Mehta

I found out what was making this program slow. In the buildST function, I pass the string digits. Since the function is recursive, and the input is fairly large, this creates many copies of the string digits thus incurring large overhead.

I declared a char digits[] at the start of the program and modified the method buildST as follows (basically same but without string digits as a parameter:

void buildST(int si, int ss, int se)
{
    if (ss == se)
    {
        segtree[si].setLeaf(digits[ss] - '0');
        return;
    }
    long left = 2 * si + 1, right = 2 * si + 2, mid = (ss + se) / 2;
    buildST(left, ss, mid);
    buildST(right, mid + 1, se);
    segtree[si].merge(segtree[left], segtree[right]);
}

This solution got accepted.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Even though I have 2 dedicate HttpGet Actions defined in my controller, only one gets called even when the URL specifies 2 different Actions

분류에서Dev

"variable might not have been initialized" even though I make sure it is

분류에서Dev

getResource not working (Even though I have a correct pathfile)

분류에서Dev

SQL code takes duplicates in, even though I've specified it not to

분류에서Dev

JAVA Runtime error in uva online judge even after formatting input

분류에서Dev

Time limit exceeded error C++

분류에서Dev

Why does my Xcode compiler tell me I use a value type even though I use classes?

분류에서Dev

Error building python package on makefile even though I have the package installed

분류에서Dev

Getting error as Cannot find name 'ProductFormComponent' even though i have added component in entryComponents array

분류에서Dev

Outgoing SSH doesn't work even though I have opened the port

분류에서Dev

Can I have an array that does not have a limit because I am getting my input by scanner?

분류에서Dev

run my code , every time i change my $(window).width()

분류에서Dev

My usb stick is not mounting. It shows in 'Disks' though where I am able to format it but even on restarting it doesn't show up normally

분류에서Dev

I have a server application that gets data exactly half the time. Why/how does this happen and how do I fix it?

분류에서Dev

Computer doesn't keep time even though on and connected to Internet

분류에서Dev

Why do I have to set LD_LIBRARY_PATH before running a program, even though I already linked the library locations in the compile stage?

분류에서Dev

How can I publish my project code online so someone can help me with it?

분류에서Dev

Name Clash even though I'm not using both interfaces

분류에서Dev

Why are .show() and .hide() toggling even though I'm not using toggle?

분류에서Dev

how can i minimize my code if i have many variables in getopt

분류에서Dev

I want to use jersey client in my code I have imported the packages still it shows error

분류에서Dev

I have a syntax error in my code for creating a trigger using sql. I use mysql version 14.14

분류에서Dev

HttpClient buffer size limit exceeded

분류에서Dev

OperationalError: stack depth limit exceeded

분류에서Dev

Online Judge Pashmak and Flowers gives runtime error

분류에서Dev

My server cannot send email even though the mail function is returning true

분류에서Dev

Java Throwing OutOfMemory Even Though (I Think) I've Set References To Null

분류에서Dev

Java Throwing OutOfMemory Even Though (I Think) I've Set References To Null

분류에서Dev

Wrote a C++ code to check if expression has balanced parenthesis and my code is not running. I have been stuck for a day now

Related 관련 기사

  1. 1

    Even though I have 2 dedicate HttpGet Actions defined in my controller, only one gets called even when the URL specifies 2 different Actions

  2. 2

    "variable might not have been initialized" even though I make sure it is

  3. 3

    getResource not working (Even though I have a correct pathfile)

  4. 4

    SQL code takes duplicates in, even though I've specified it not to

  5. 5

    JAVA Runtime error in uva online judge even after formatting input

  6. 6

    Time limit exceeded error C++

  7. 7

    Why does my Xcode compiler tell me I use a value type even though I use classes?

  8. 8

    Error building python package on makefile even though I have the package installed

  9. 9

    Getting error as Cannot find name 'ProductFormComponent' even though i have added component in entryComponents array

  10. 10

    Outgoing SSH doesn't work even though I have opened the port

  11. 11

    Can I have an array that does not have a limit because I am getting my input by scanner?

  12. 12

    run my code , every time i change my $(window).width()

  13. 13

    My usb stick is not mounting. It shows in 'Disks' though where I am able to format it but even on restarting it doesn't show up normally

  14. 14

    I have a server application that gets data exactly half the time. Why/how does this happen and how do I fix it?

  15. 15

    Computer doesn't keep time even though on and connected to Internet

  16. 16

    Why do I have to set LD_LIBRARY_PATH before running a program, even though I already linked the library locations in the compile stage?

  17. 17

    How can I publish my project code online so someone can help me with it?

  18. 18

    Name Clash even though I'm not using both interfaces

  19. 19

    Why are .show() and .hide() toggling even though I'm not using toggle?

  20. 20

    how can i minimize my code if i have many variables in getopt

  21. 21

    I want to use jersey client in my code I have imported the packages still it shows error

  22. 22

    I have a syntax error in my code for creating a trigger using sql. I use mysql version 14.14

  23. 23

    HttpClient buffer size limit exceeded

  24. 24

    OperationalError: stack depth limit exceeded

  25. 25

    Online Judge Pashmak and Flowers gives runtime error

  26. 26

    My server cannot send email even though the mail function is returning true

  27. 27

    Java Throwing OutOfMemory Even Though (I Think) I've Set References To Null

  28. 28

    Java Throwing OutOfMemory Even Though (I Think) I've Set References To Null

  29. 29

    Wrote a C++ code to check if expression has balanced parenthesis and my code is not running. I have been stuck for a day now

뜨겁다태그

보관