Skip to content

Instantly share code, notes, and snippets.

@algmyr
Created June 27, 2019 14:56
Show Gist options
  • Save algmyr/b8b76cddf5ae70e79fe6e44b164271f1 to your computer and use it in GitHub Desktop.
Save algmyr/b8b76cddf5ae70e79fe6e44b164271f1 to your computer and use it in GitHub Desktop.
io
struct FastI {
char cur;
char tmp[1 << 8];
#ifdef _WIN32
char nextChar() {
return cur=_getchar_nolock();
}
#else
static constexpr int BUFSIZE = 1<<14;
char buf[BUFSIZE];
int i = 0;
int sz = 0;
char nextChar() {
if (i == sz) {
sz = fread_unlocked(buf, sizeof(char), BUFSIZE, stdin);
i = 0;
}
return cur = buf[i++];
}
#endif
char peekChar() const { return cur; }
operator bool() const { return peekChar(); }
bool isBlank(char c) const { return (c < '-' && c); }
bool skipBlanks() {
while (isBlank(nextChar()));
return peekChar() != 0;
}
FastI& operator>>(char& c) {
c = nextChar();
return *this;
}
FastI& operator>>(char* buf) {
string s; (*this) >> s;
copy(all(s), buf);
buf[s.size()] = '\0';
return *this;
}
FastI& operator>>(string& s) {
if (skipBlanks()) {
s.clear();
s += peekChar();
while (!isBlank(nextChar())) s += peekChar();
}
return *this;
}
FastI& operator>>(double& d) {
if ((*this) >> tmp) d = atof(tmp);
return *this;
}
template <typename Integer,
typename = std::enable_if_t<std::is_integral<Integer>::value>>
FastI& operator>>(Integer& n) {
if (skipBlanks()) {
int sign = +1;
if (peekChar() == '-') {
sign = -1;
nextChar();
}
n = peekChar() - '0';
while (!isBlank(nextChar())) {
n += n + (n << 3) + peekChar() - 48;
}
n *= sign;
}
return *this;
}
} __fasti__;
struct FastO {
char tmp[1 << 8];
void putChar(char c) {
#ifdef _WIN32
_putchar_nolock(c);
#else
putc_unlocked(c, stdout);
#endif
}
void putStr(const char* s, int len) {
for (int i = 0; i < len; ++i) putChar(s[i]);
}
FastO& operator<<(char c) { putChar(c); return *this; }
FastO& operator<<(const char* s) { putStr(s, strlen(s)); return *this; }
FastO& operator<<(const string& s) {
putStr(s.data(), s.size());
return *this;
}
FastO& operator<<(double d) { return (*this) << to_string(d); }
template <typename Integer,
typename = std::enable_if_t<std::is_integral<Integer>::value>>
char* toString(Integer n) {
// Can everyone support C++17 soon?
//auto [end,err] = to_chars(tmp, tmp+30, n);
//*end = '\0';
//return tmp;
char * p = (tmp + 30);
if (n) {
bool isNeg = 0;
if (n < 0) isNeg = 1, n = -n;
while (n) *--p = n%10 + '0', n /= 10;
if (isNeg) *--p = '-';
} else
*--p = '0';
return p;
}
template <typename Integer,
typename = std::enable_if_t<std::is_integral<Integer>::value>>
FastO& operator << (Integer n) { return (*this) << toString(n); }
} __fasto__;
#define endl ('\n')
#define cout __fasto__
#define cin __fasti__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment