-10

This is a problem on codeforces and I have submitted a solution and I got TLE. How to remove TLE

#include<bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    unsigned int y, k, n;
    set <int> s;
    cin >> y >> k >> n;
    if (y >= n)
    {
        cout << -1; return 0;
    }
    for (int i = y + 1; i <= n; i++)
    {
        if (i%k == 0)
        {
            s.insert(i - y);
        }
    }
    if (s.begin() == s.end())
    {
        cout << -1; return 0;
    }
    for (auto x : a)
        cout << x << " ";
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 5
    While you're waiting for an answer, please read [Why should I not #include ?](https://stackoverflow.com/q/31816095/5470596) and [Why is “using namespace std” considered bad practice?](https://stackoverflow.com/q/1452721/5470596) ;) – YSC Jan 24 '19 at 17:17
  • 1
    But before that, [edit] your question to explain what you're program is supposed to do, and how it does it. That's considered better than simply pointing to a link nobody will follow. – YSC Jan 24 '19 at 17:18
  • 3
    You need to come up with a smarter algorithm. – n. m. could be an AI Jan 24 '19 at 17:34
  • 2
    Where, oh where, did you get the idea of using #include ?? Wherever that is you should stop getting ideas from there – Dr t Jan 24 '19 at 17:44
  • 1
    _@VaibhavPandey_ Stop wasting your time with such _online code judge_ engines. Go and work through a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead. – πάντα ῥεῖ Jan 24 '19 at 18:18
  • You have provided no input, nor expected output, nor duration ... see [MCVE] – 2785528 Jan 24 '19 at 18:20

1 Answers1

2

The problem seems at the algorithmic level. Instead to generate all candidate i values and then test if they are divisible by k, you can directly generate these values in a loop with an increment equal to k.

The minimum value iminis equal to k*((y+1)/k) or k*((y+1)/k) + k, depending if y+1 is divisible by kor not.

You have two gains: you consider k less candidates, and you avoid the costly % operation.

Moreover, when you find a value, you can directly print it, no need to memorize it.

Edit: here is the code

#include <iostream>

int main()
{
    std::ios::sync_with_stdio(false);
    unsigned int y, k, n;
    std::cin >> y >> k >> n;

    unsigned int imin = k*((y+1)/k);
    if (imin < y+1) imin += k;
    if (imin > n) {
        std::cout << -1;
        return 0;
    }

    for (unsigned int i = imin; i <= n; i+=k)
    {
        std::cout << i-y << " ";
    }
    return 0;
}

Edit 2: the last i-y calculation can be avoided by changing the bounds of the loop

Damien
  • 4,809
  • 4
  • 15
  • 20