How to optimize printing out the difference between the greater and the lesser of two integers?

China☆狼群 提交于 2019-12-05 16:03:08

I would try to eliminate IO operations. Read one block of data (as big as you can). Compute the outputs, write them to another string then write that string out.

You sscanf or stringstream equivalents to read/write from your memory blocks.

IO usually needs to go through the kernel so there's a small chance that you would loose the CPU for a bit. There's also some cost(time) associated with it. It's small but you are trying to run in less than 10ms.

printf is a swiss army knife. It knows many ways to format its arguments, and that can be any number. In this case, you want a single dedicated function, so you don't wast time scanning for the single occurrence of %d. (BTW, this is a speed benefit of std::cout << - the compiler sorts out the overloading at compile time).

Once you have that single formatting function, make it output to a single char[] and call puts on that. As puts does no formatting of its own, it can be much faster than printf.

Here is my variant with assembler routines.

#include <iostream>
#include <string>

using namespace std;

int main()
{
   unsigned long long i, j;
   string outv;   
   while(cin >> i >> j) {
     asm("movq %0, %%rax;"
         "movq %1, %%rdx;"  
         "subq %%rax, %%rdx;"
         "jns .L10;"        
         "notq %%rdx;"      
         "addq $0b1, %%rdx;"
         ".L10: movq %%rdx, %0": : "g"(i), "g"(j) );       
     string str = to_string(i);
     outv += str + "\n";     
    }
    cout << outv;   
 }

The trick is using :

This solution which runs in less than 0.001 seconds , is based on UVa Online Judge submission http://ideone.com/ca8sDu that was solved by http://uhunt.felix-halim.net/id/779215 ; However this Solution is Abridged and modified #include

#define pll(n) printf("%lld ",(n))
#define plln(n) printf("%lld\n",(n))
typedef long long ll;

#if defined(_WINDOWS) // On Windows GCC, use the slow thread safe version
inline int getchar_unlocked() {
    return getchar();
}
#elif defined  (_MSC_VER)// On   Visual Studio
inline int getchar_unlocked(){
    return _getchar_nolock(); // use Microsoft Thread unsafe version
}
#endif 

inline int  scn( ll & n){
     n = 0;
     int  c = getchar_unlocked(),t=0;
    if (c == EOF) 
        return 0;
    while(c < '0' || c > '9') {
        if(c==45)
            t=1;
        c = getchar_unlocked(); 
    }
    while(c >= '0' && c <= '9'){
        n = n *10+ c - '0';       
        c = getchar_unlocked();
    }
    if(t!=0)
        n *=-1;
    return 1;
}

int main(){
    ll n, m;
    while(scn(n)+scn(m)==2){
        if (n>m)
            plln(n - m);
        else
            plln(m - n);
    }
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!