Stories

Detail Return Return

焦糖餅乾頭文件c++最新同步 - Stories Detail

\(\color{green}正在更新\)

windos-2.0

點擊查看代碼
#define _WIN32_WINNT 0x0601
//#pragma cpp_std c++11 
//你可以換成指令: -std=gnu++11
#include <bits/stdc++.h>
#include <Windows.h>
#include <string>
#include <algorithm>
#include <stdexcept>
#include <cctype>
#include <mutex>
#include <fstream>
#include <chrono>
#include <conio.h>
#include <limits>    // 用於清除輸入緩衝區
#include <wininet.h>
#include <shlobj.h>
#include <powrprof.h>
#include <lmaccess.h>
#include <tlhelp32.h>
#include <commctrl.h>
#include <shellapi.h>
#include <mmsystem.h>
#include <psapi.h>
#include <thread>
#include <vector>
#include <map>
//#include <unistd.h> linux/macOS
using namespace std;

//你需要定義 _agree_ 表示同意 CC BY-NC-ND 4.0
#ifndef _agree_
#undef _JTBG_H_
#define _JTBG_H_
#endif

#ifndef _JTBG_H_
#define _JTBG_H_
#define MUL(a,b) (a)*(b)
#define __JTBG_NORETURN(a) ext(a)
#define MUS(a,b) (a)-(b)
#define PLS(a,b) (a)+(b)
#define DEF(a,b) (a)/(b)
class MD5 
{
private:
    typedef unsigned int uint32;
    typedef unsigned long long uint64;

    struct Context 
	{
        uint32 state[4];
        uint32 count[2];
        unsigned char buffer[64];
    };

    static void init(Context &ctx) 
	{
        ctx.count[0] = ctx.count[1] = 0;
        ctx.state[0] = 0x67452301;
        ctx.state[1] = 0xefcdab89;
        ctx.state[2] = 0x98badcfe;
        ctx.state[3] = 0x10325476;
    }

    static void update(Context &ctx, const unsigned char *input, size_t length) 
	{
        uint32 i, index, partLen;

        index = (uint32)((ctx.count[0] >> 3) & 0x3F);
        if ((ctx.count[0] += ((uint32)length << 3)) < ((uint32)length << 3))
            ctx.count[1]++;
        ctx.count[1] += (uint32)(length >> 29);

        partLen = 64 - index;
        if (length >= partLen) 
		{
            memcpy(&ctx.buffer[index], input, partLen);
            transform(ctx.state, ctx.buffer);
            for (i = partLen; i + 63 < length; i += 64)
                transform(ctx.state, &input[i]);
            index = 0;
        } 
		else
		{
            i = 0;
        }
        memcpy(&ctx.buffer[index], &input[i], length - i);
    }

    static void final(unsigned char digest[16], Context &ctx) 
	{
        unsigned char padding[64] = {0x80};
        unsigned char bits[8];
        size_t index, padLen;

        encode(bits, ctx.count, 8);
        index = (uint32)((ctx.count[0] >> 3) & 0x3f);
        padLen = (index < 56) ? (56 - index) : (120 - index);
        update(ctx, padding, padLen);
        update(ctx, bits, 8);
        encode(digest, ctx.state, 16);
    }

    static void transform(uint32 state[4], const unsigned char block[64]) 
	{
        uint32 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
        decode(x, block, 64);

        FF(a, b, c, d, x[0], 7, 0xd76aa478);
        FF(d, a, b, c, x[1], 12, 0xe8c7b756);
        FF(c, d, a, b, x[2], 17, 0x242070db);
        FF(b, c, d, a, x[3], 22, 0xc1bdceee);
        FF(a, b, c, d, x[4], 7, 0xf57c0faf);
        FF(d, a, b, c, x[5], 12, 0x4787c62a);
        FF(c, d, a, b, x[6], 17, 0xa8304613);
        FF(b, c, d, a, x[7], 22, 0xfd469501);
        FF(a, b, c, d, x[8], 7, 0x698098d8);
        FF(d, a, b, c, x[9], 12, 0x8b44f7af);
        FF(c, d, a, b, x[10], 17, 0xffff5bb1);
        FF(b, c, d, a, x[11], 22, 0x895cd7be);
        FF(a, b, c, d, x[12], 7, 0x6b901122);
        FF(d, a, b, c, x[13], 12, 0xfd987193);
        FF(c, d, a, b, x[14], 17, 0xa679438e);
        FF(b, c, d, a, x[15], 22, 0x49b40821);

        GG(a, b, c, d, x[1], 5, 0xf61e2562);
        GG(d, a, b, c, x[6], 9, 0xc040b340);
        GG(c, d, a, b, x[11], 14, 0x265e5a51);
        GG(b, c, d, a, x[0], 20, 0xe9b6c7aa);
        GG(a, b, c, d, x[5], 5, 0xd62f105d);
        GG(d, a, b, c, x[10], 9, 0x02441453);
        GG(c, d, a, b, x[15], 14, 0xd8a1e681);
        GG(b, c, d, a, x[4], 20, 0xe7d3fbc8);
        GG(a, b, c, d, x[9], 5, 0x21e1cde6);
        GG(d, a, b, c, x[14], 9, 0xc33707d6);
        GG(c, d, a, b, x[3], 14, 0xf4d50d87);
        GG(b, c, d, a, x[8], 20, 0x455a14ed);
        GG(a, b, c, d, x[13], 5, 0xa9e3e905);
        GG(d, a, b, c, x[2], 9, 0xfcefa3f8);
        GG(c, d, a, b, x[7], 14, 0x676f02d9);
        GG(b, c, d, a, x[12], 20, 0x8d2a4c8a);

        HH(a, b, c, d, x[5], 4, 0xfffa3942);
        HH(d, a, b, c, x[8], 11, 0x8771f681);
        HH(c, d, a, b, x[11], 16, 0x6d9d6122);
        HH(b, c, d, a, x[14], 23, 0xfde5380c);
        HH(a, b, c, d, x[1], 4, 0xa4beea44);
        HH(d, a, b, c, x[4], 11, 0x4bdecfa9);
        HH(c, d, a, b, x[7], 16, 0xf6bb4b60);
        HH(b, c, d, a, x[10], 23, 0xbebfbc70);
        HH(a, b, c, d, x[13], 4, 0x289b7ec6);
        HH(d, a, b, c, x[0], 11, 0xeaa127fa);
        HH(c, d, a, b, x[3], 16, 0xd4ef3085);
        HH(b, c, d, a, x[6], 23, 0x04881d05);
        HH(a, b, c, d, x[9], 4, 0xd9d4d039);
        HH(d, a, b, c, x[12], 11, 0xe6db99e5);
        HH(c, d, a, b, x[15], 16, 0x1fa27cf8);
        HH(b, c, d, a, x[2], 23, 0xc4ac5665);

        II(a, b, c, d, x[0], 6, 0xf4292244);
        II(d, a, b, c, x[7], 10, 0x432aff97);
        II(c, d, a, b, x[14], 15, 0xab9423a7);
        II(b, c, d, a, x[5], 21, 0xfc93a039);
        II(a, b, c, d, x[12], 6, 0x655b59c3);
        II(d, a, b, c, x[3], 10, 0x8f0ccc92);
        II(c, d, a, b, x[10], 15, 0xffeff47d);
        II(b, c, d, a, x[1], 21, 0x85845dd1);
        II(a, b, c, d, x[8], 6, 0x6fa87e4f);
        II(d, a, b, c, x[15], 10, 0xfe2ce6e0);
        II(c, d, a, b, x[6], 15, 0xa3014314);
        II(b, c, d, a, x[13], 21, 0x4e0811a1);
        II(a, b, c, d, x[4], 6, 0xf7537e82);
        II(d, a, b, c, x[11], 10, 0xbd3af235);
        II(c, d, a, b, x[2], 15, 0x2ad7d2bb);
        II(b, c, d, a, x[9], 21, 0xeb86d391);

        state[0] += a;
        state[1] += b;
        state[2] += c;
        state[3] += d;
    }

    static inline uint32 F(uint32 x, uint32 y, uint32 z) { return (x & y) | (~x & z); }
    static inline uint32 G(uint32 x, uint32 y, uint32 z) { return (x & z) | (y & ~z); }
    static inline uint32 H(uint32 x, uint32 y, uint32 z) { return x ^ y ^ z; }
    static inline uint32 I(uint32 x, uint32 y, uint32 z) { return y ^ (x | ~z); }

    static inline void FF(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 t) 
	{
        a += F(b, c, d) + x + t;
        a = (a << s) | (a >> (32 - s));
        a += b;
    }

    static inline void GG(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 t) 
	{
        a += G(b, c, d) + x + t;
        a = (a << s) | (a >> (32 - s));
        a += b;
    }

    static inline void HH(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 t) 
	{
        a += H(b, c, d) + x + t;
        a = (a << s) | (a >> (32 - s));
        a += b;
    }

    static inline void II(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 t) 
	{
        a += I(b, c, d) + x + t;
        a = (a << s) | (a >> (32 - s));
        a += b;
    }

    static void encode(unsigned char *output, const uint32 *input, size_t length) 
	{
        for (size_t i = 0, j = 0; j < length; i++, j += 4) 
		{
            output[j] = (unsigned char)(input[i] & 0xFF);
            output[j + 1] = (unsigned char)((input[i] >> 8) & 0xFF);
            output[j + 2] = (unsigned char)((input[i] >> 16) & 0xFF);
            output[j + 3] = (unsigned char)((input[i] >> 24) & 0xFF);
        }
    }

    static void decode(uint32 *output, const unsigned char *input, size_t length) 
	{
        for (size_t i = 0, j = 0; j < length; i++, j += 4)
            output[i] = ((uint32)input[j]) | (((uint32)input[j + 1]) << 8) |
                       (((uint32)input[j + 2]) << 16) | (((uint32)input[j + 3]) << 24);
    }

public:
    static std::string hash(const std::string &input) 
	{
        Context ctx;
        init(ctx);
        update(ctx, (const unsigned char*)input.c_str(), input.length());
        unsigned char digest[16];
        final(digest, ctx);
        char hex_str[33];
        for (int i = 0; i < 16; i++)
            sprintf(hex_str + i * 2, "%02x", digest[i]);
        hex_str[32] = '\0';
        return std::string(hex_str);
    }
};
//MD5::hash(str)

unsigned long long pHash(const string& s) 
{
    const unsigned long long base = 911382629ULL;
    const unsigned long long mod = 1000000000000000003ULL;
    unsigned long long hashValue = 0;
    
    // 使用傳統for循環兼容C++98
    for (size_t i = 0; i < s.size(); ++i) 
	{
        char c = s[i];
        hashValue = (hashValue * base + static_cast<unsigned long long>(c)) % mod;
    }
    
    return hashValue;
}

struct StringHash 
{
    static const unsigned long long base = 911382629ULL;
    static const unsigned long long mod = 1000000000000000003ULL;
    vector<unsigned long long> hash;
    vector<unsigned long long> power;
    StringHash(const string& s) 
	{
        int n = s.size();
        hash.resize(n + 1);
        power.resize(n + 1);
        power[0] = 1;
        
        for (int i = 0; i < n; ++i) {
            hash[i+1] = (hash[i] * base + static_cast<unsigned long long>(s[i])) % mod;
            power[i+1] = (power[i] * base) % mod;
        }
    }
    // 獲取子串s[l..r]的哈希值(0-based,包含l和r)
    unsigned long long getHash(int l, int r) 
	{
        int len = r - l + 1;
        unsigned long long res = (hash[r+1] - hash[l] * power[len]) % mod;
        return res < 0 ? res + mod : res;
    }
};
//StringHash strHash(str);
//cout << "前綴哈希完整字符串: " << strHash.getHash(0, str.size()-1) << endl;
//cout << "子串哈希(0-4): " << strHash.getHash(0, 4) << " (對應\"Hello\")" << endl;

size_t Hash(const string& s) 
{
    size_t hashVal = 0;
    for (size_t i = 0; i < s.size(); ++i) 
	{
        // 簡單的哈希組合算法
        hashVal = hashVal * 31 + static_cast<size_t>(s[i]);
    }
    return hashVal;
}    

struct Save
{
	string path;
	int errorlevel=-1;
	ifstream save_i;
	ofstream save_o;
	void setpt(string s)
	{
		path=s;
		return ;
	}
	void read_nol()
	{
		save_i.open(path.c_str());
		if(!save_i.good()) errorlevel=1100;
		return ;
	}
	void read_bin()
	{
		save_i.open(path.c_str(),ios::in|ios::binary);
		if(!save_i.good()) errorlevel=1100;
		return ;
	}
	void save_nol()
	{
		save_o.open(path.c_str());
		if(!save_o.good()) errorlevel=1000;
		return ;
	}
	void save_app()
	{
		save_o.open(path.c_str(),ios::app|ios::out);
		if(!save_o.good()) errorlevel=1000;
		return ;
	}
	void save_bin()
	{
		save_o.open(path.c_str(),ios::binary|ios::out);
		if(!save_o.good()) errorlevel=1000;
		return ;
	}
	//save_o.write(s.data(),s.size());
	void save_stop()
	{
//		save_i.close();
		save_o.close();
		return ;
	}
	void read_stop()
	{
		save_i.close();
//		save_o.close();
		return ;
	}
};

string FileMD5(string path)
{
	ifstream file(path,ios::in|ios::binary);
	if (!file.is_open()) 
	{
		return "";
	}
	string fileContent;
	file.seekg(0,ios::end);
	size_t fileSize = static_cast<size_t>(file.tellg());
	file.seekg(0,ios::beg);
	fileContent.reserve(fileSize);
	fileContent.assign(std::istreambuf_iterator<char>(file),std::istreambuf_iterator<char>());
	if (!file && !file.eof()) 
	{
		return "";
	}
	return MD5::hash(fileContent);
}

void say(string s,int t)
{
	if(t<0) return ;
	int len=int(s.length());
	for(int i=0;i<len;i++)
	{
		cout<<s[i];
		Sleep(t);
	}
	return ;
}

void pause(string s) 
{
    cout<<s<<endl;
    system("pause > nul");
	return ;
}

int ext(int num)
{
	cout<<"[jtbg.h] Process exited with return value "<<num<<endl;
	exit(num);
	return num;
}

template <typename to_string_T>
string tostring(to_string_T k)
{
	stringstream ans;
	ans<<k;
	return ans.str();
}

int chkey(int t)
{
	if(t!=-1)
	{
		t*=100;
		while(t--) 
		{
        	if (_kbhit()) 
			{
         	   int key = _getch();
         	   return key;
       	 	}
   		}
		return -1;
	}
	else
	{
		while(1) 
		{
        	if (_kbhit()) 
			{
         	   int key = _getch();
         	   return key;
        	}
    	}
	}
}

enum Color 
{
    BLACK = 0,
    BLUE = 1,
    GREEN = 2,
    CYAN = 3,
    RED = 4,
    MAGENTA = 5,
    BROWN = 6,
    LIGHT_GRAY = 7,
    DARK_GRAY = 8,
    LIGHT_BLUE = 9,
    LIGHT_GREEN = 10,
    LIGHT_CYAN = 11,
    LIGHT_RED = 12,
    LIGHT_MAGENTA = 13,
    YELLOW = 14,
    WHITE = 15
};

void scg(Color x,Color y)
{
	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    // 設置文本顏色和背景顏色,高4位是背景,低4位是文本
    SetConsoleTextAttribute(hConsole, (y << 4) | x);
	return ;
}

void scg(int x,int y)
{
	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    // 設置文本顏色和背景顏色,高4位是背景,低4位是文本
    SetConsoleTextAttribute(hConsole, (y << 4) | x);
	return ;
}

void set_back_color()
{
	scg(7,0);
	return ;
}

int rd(int a,int b)
{
	srand(GetTickCount()+rand());
	return a+rand()%(b+1);
}

enum TimeType
{
	yer=0,
	mon=1,
	dat=2,
	hor=3,
	mit=4,
	sec=5,
	mst=6,
};
int Gettime(TimeType x)
{
	time_t now = time(0);
	tm *localTime = localtime(&now);
	if(x==0) return 1900 + localTime->tm_year;//年份
	if(x==1) return 1 + localTime->tm_mon;//月份
	if(x==2) return localTime->tm_mday;//日期
	if(x==3) return localTime->tm_hour;//小時
	if(x==4) return localTime->tm_min;//分鐘
	if(x==5) return localTime->tm_sec;//秒
	if(x==6) return GetTickCount();//ms
	return -1;
}
int Gettime(string x)
{
	time_t now = time(0);
	tm *localTime = localtime(&now);
	if(x=="year") return 1900 + localTime->tm_year;//年份
	if(x=="mon") return 1 + localTime->tm_mon;//月份
	if(x=="dat") return localTime->tm_mday;//日期
	if(x=="hor") return localTime->tm_hour;//小時
	if(x=="mit") return localTime->tm_min;//分鐘
	if(x=="sec") return localTime->tm_sec;//秒
	if(x=="mst") return GetTickCount();//ms
	return -1;
}

//控制枱光標位置控制
void setcursor(int x,int y) 
{
	COORD coord;
	coord.X = x;
	coord.Y = y;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

//隱藏/顯示控制枱光標
void setCVis(bool visible) 
{
	CONSOLE_CURSOR_INFO cursorInfo = {1, visible};
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
}

//獲取控制枱尺寸
void getCSize(int &width,int &height) 
{
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
	width = csbi.srWindow.Right - csbi.srWindow.Left + 1;
	height = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
}

//生成指定長度的隨機字符串
string randS(int length) 
{
	const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	string result;
	for (int i = 0; i < length; ++i) {
		result += chars[rand() % chars.size()];
	}
	return result;
}

//計算文件大小(字節)
long long getFileSize(const string &filename)
{
	ifstream file(filename, ios::binary | ios::ate);
	if(!file.good()) return -1;
	return static_cast<long long>(file.tellg());
}

//延遲函數(高精度ms)
void msSleep(int milliseconds) 
{
	auto start = chrono::high_resolution_clock::now();
	while (chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start).count() < milliseconds);
}

//檢測文件讀寫是否
bool fileok(const string &filename) 
{
	ifstream file(filename);
	return file.good();
}

//清除控制枱指定區域內容
void clearCA(int x, int y, int width, int height) 
{
	for(int i=0;i<height;i++)
	{
		setcursor(x, y + i);
		cout << string(width, ' ');
	}
}

//計算文件夾內文件數量(僅統計一級目錄)
int getFileCountInDir(const string& dirPath) {
	int count = 0;
	WIN32_FIND_DATA findData;
	HANDLE hFind = FindFirstFile((dirPath + "\\*").c_str(), &findData);
	if (hFind == INVALID_HANDLE_VALUE) return -1;
	do 
	{
		if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) 
		{
			count++; // 只統計文件,不統計文件夾
		}
	} while (FindNextFile(hFind, &findData) != 0);
	FindClose(hFind);
	return count;
}

double random(double min, double max) 
{
	return min + (max - min) * (rand() / (double)RAND_MAX);
}

//檢查字符串是否為數字(整數或小數)
bool isNumber(const string& str) 
{
	if (str.empty()) return false;
	size_t start = 0;
	if (str[0] == '+' || str[0] == '-') start = 1;
	bool hasDot = false;
	for (size_t i = start; i < str.size(); ++i) 
	{
		if (str[i] == '.') 
		{
			if (hasDot) return false;
			hasDot = true;
		}
		else if (!isdigit(str[i])) 
		{
			return false;
		}
	}
	return true;
}

struct memory
{
	long long bytes;
	double toB()
	{
		return static_cast<double>(bytes);
	}
	double toKB()
	{
		const double KB = 1024.0;
		return bytes / KB;
	}
	double toMB()
	{
		const double MB = 1024.0 * 1024.0;
		return bytes / MB;
	}
	double toGB()
	{
		const double GB = 1024.0 * 1024.0 * 1024.0;
		return bytes / GB;
	}
	double toTB()
	{
		const double TB = 1024.0 * 1024.0 * 1024.0 * 1024.0;
		return bytes / TB;
	}
	double toPB()
	{
		const double PB = 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0;
		return bytes / PB;
	}
};

// 將字節轉換為B(字節)
double rtoB(int bytes)
{
	return static_cast<double>(bytes);
}
// 將字節轉換為KB(千字節)
double rtoKB(int bytes)
{
	const double KB = 1024.0;
	return bytes / KB;
}
// 將字節轉換為MB(兆字節)
double rtoMB(int bytes)
{
	const double MB = 1024.0 * 1024.0;
	return bytes / MB;
}
// 將字節轉換為GB(千兆字節)
double rtoGB(int bytes)
{
	const double GB = 1024.0 * 1024.0 * 1024.0;
	return bytes / GB;
}
// 將字節轉換為TB(太字節)
double rtoTB(int bytes)
{
	const double TB = 1024.0 * 1024.0 * 1024.0 * 1024.0;
	return bytes / TB;
}
// 將字節轉換為PB(拍字節)
double rtoPB(int bytes)
{
	const double PB = 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0;
	return bytes / PB;
}

void lowerstring(string &s)
{
	for(int i=0;i<int(s.size());i++)
	{
		if(s[i]>='A'&&s[i]<='Z')
		{
			s[i]=s[i]-'A'+'a';
		}
	}
	return ;
}
void uperstring(string &s)
{
	for(int i=0;i<int(s.size());i++)
	{
		if(s[i]>='a'&&s[i]<='z')
		{
			s[i]=s[i]-'a'+'A';
		}
	}
	return ;
}

void flushed() 
{
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	cin.clear();
	return ;
}

//xor加/解密
string xorpass(const string &str, const string &key) 
{
	string result = str;
	size_t keyLen = key.size();
	if (keyLen == 0) return result;
	for (size_t i = 0; i < result.size(); ++i)
	{
		result[i] ^= key[i % keyLen];
	}
	return result;
}

string base64up(const string &str,const string &base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") 
{
	
	string result;
	int val = 0, valBits = 0;
	for (unsigned char c : str) 
	{
		val = (val << 8) + c;
		valBits += 8;
		while (valBits >= 6)
		{
			result += base64Chars[(val >> (valBits - 6)) & 0x3F];
			valBits -= 6;
		}
	}
	if (valBits > 0) 
	{
		val <<= (6 - valBits);
		result += base64Chars[val & 0x3F];
	}
	while (result.size() % 4 != 0) 
	{
		result += '=';
	}
	return result;
}
string base64dec(const string &str,const string base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") 
{
	string result;
	vector<int> val(4, -1); 
	for (size_t i = 0; i < str.size(); ++i) 
	{
		char c = str[i];
		if (c == '=') break;
		size_t pos = base64Chars.find(c);
		if (pos == string::npos) continue;
		val[i % 4] = pos;
		if (i % 4 == 3) 
		{
			result += (val[0] << 2) + ((val[1] >> 4) & 0x3);
			if (val[2] != -1) 
			{
				result += ((val[1] << 4) & 0xF0) + ((val[2] >> 2) & 0xF);
			}
			if (val[3] != -1) 
			{
				result += ((val[2] << 6) & 0xC0) + val[3];
			}
			val.assign(4, -1);
		}
	}
	return result;
}

void Testsuper(string &s) 
{
	if (s.empty()) return;
	s[0] = toupper(s[0]);
	for (size_t i = 1; i < s.size();i++) 
	{
		s[i]=tolower(s[i]);
	}
}

struct Timer
{
	private:
		using Clock = std::chrono::high_resolution_clock;
		using TimePoint = std::chrono::time_point<Clock>;
		
		TimePoint start_;
		TimePoint pause_;
		bool isRunning_;
		std::chrono::duration<double> elapsed_;
		
	public:
		Timer() : isRunning_(false), elapsed_(0) {}
		void starttick() 
		{
			if (!isRunning_) 
			{
				start_ = Clock::now();
				isRunning_ = true;
			}
		}
		void pausetick() 
		{
			if (isRunning_) 
			{
				pause_ = Clock::now();
				elapsed_ += pause_ - start_;
				isRunning_ = false;
			}
		}
		void resettick() 
		{
			isRunning_ = false;
			elapsed_ = std::chrono::duration<double>(0);
		}
		double timesec() 
		const 
		{
			if (isRunning_) 
			{
				auto now = Clock::now();
				return (elapsed_ + (now - start_)).count();
			}
			return elapsed_.count();
		}
		double timemst() 
		const 
		{
			return timesec() * 1000.0;
		}
};

#ifndef _NOMATH_
#define _NOMATH_
constexpr double PI = 3.14159265358979323846264338327950288419716939937510582097494459;
constexpr double E = 2.71828182845904523536;
constexpr double SQRT2 = 1.41421356237309504880;
constexpr double DEG_TO_RAD = PI / 180.0;  // 角度轉弧度係數
constexpr double RAD_TO_DEG = 180.0 / PI;  // 弧度轉角度係數
//角度轉弧度
inline double toRadians(double degrees) 
{
	return degrees * DEG_TO_RAD;
}

// 弧度轉角度
inline double toDegrees(double radians) 
{
	return radians * RAD_TO_DEG;
}

// 計算階乘
inline long long fac(int n) 
{
	if(n<0) return -1;
	long long result = 1;
	for (int i = 2; i <= n; ++i) 
	{
		result *= i;
	}
	return result;
}

double qpow(double base, int exponent) 
{
	if (exponent==0) return 1.0;
	if (base==0) return 0.0;
	bool isNegative = exponent < 0;
	unsigned int absExponent = static_cast<unsigned int>(isNegative ? -exponent : exponent);
	double result = 1.0;
	double current = base;
	while (absExponent > 0) 
	{
		if (absExponent % 2 == 1) 
		{
			result *= current;
		}
		current *= current;   
		absExponent /= 2;       
	}
	return isNegative ? 1.0 / result : result;
}

long long A(int a, int b) 
{
	if(a < 0 || b < 0 || a < b) 
	{
		return -1;
	}
	if (b == 0) 
	{ 
		return 1;
	}
	long long result = 1;
	for (int i = 0; i < b; ++i) 
	{
		result *= (a - i);
		if (result < 0) 
		{
			return -1;
		}
	}
	return result;
}

long long C(int a, int b)
{
	if (a < 0 || b < 0 || a < b) 
	{
		return -1;
	}
	if (b == 0 || a == b) 
	{ 
		return 1;
	}
	b = min(b, a - b);
	long long result = 1;
	for (int i = 1; i <= b; ++i) 
	{
		result = result * (a - b + i) / i;
		if (result < 0) 
		{
			return -1;
		}
	}
	return result;
}

bool isHe(int x)
{
	if(x<2) return 0;
	for(int i=2;i*i<=x;i++)
	{
		if(x%i==0) return 0;
	}
	return 1;
}
#endif

#ifndef _NOSHORT_
#define _NOSHORT_
#define syst system("cls")
#define sys(x) system(x)
#define no_pause() system("pause > nul") 
#define pause() system("pause")
#define to_int(x) stoi(x)                   // 轉換為int類型
#define to_long(x) stol(x)                  // 轉換為long類型
#define to_double(x) stod(x)                // 轉換為double類型
#define to_str(x) tostring(x)               // 轉換為string類型
#define sleep(ms) Sleep(ms)                 // 延遲指定毫秒數
#define time_now() time(0)                  // 獲取當前時間戳(秒級)
#define getms() GetTickCount()
#define shuta() system("shutdown -a")
#define shuts() system("shutdown -s -t 0")
#define shutr() system("shutdown -g -t 0")
#define about() jtbg_h_about()
#endif

struct logger
{
	Save rep;
	enum error_type
	{
		error=0,
		info=1,
		warn=2,
		debug=3,
	};
	void reset_logger(string path)
	{
		rep.setpt(path);
		rep.save_nol();
		rep.save_o<<"["<<Gettime(yer)<<"/"<<Gettime(mon)<<"/"<<Gettime(dat)<<"-"<<Gettime(hor)<<":"<<Gettime(mit)<<":"<<Gettime(sec)<<"]"<<endl;
		return ;
	}
	void report(string s,error_type tp)
	{
		rep.save_o<<"["<<Gettime(hor)<<":"<<Gettime(mit)<<":"<<Gettime(sec)<<"("<<Gettime(mst)%1000<<")] ";
		if(tp==0) rep.save_o<<"{type=error} ";
		else if(tp==1) rep.save_o<<"{type=info} ";
		else if(tp==2) rep.save_o<<"{type=warn} ";
		else if(tp==3) rep.save_o<<"{type=debug} ";
		else rep.save_o<<"{type=unknow} ";
		rep.save_o<<s<<endl;
		flush(rep.save_o);
		return ;
	}
	void stop()
	{
		rep.save_stop();
		return ;
	}
};

void thred(logger p,string s)
{
	p.report(s,logger::error);
	return ;
}

string xorFile(const string& filePath,const string& key) 
{
	if (key.empty()) 
	{
		return "";
	}
	std::ifstream file(filePath.c_str(), std::ios::in | std::ios::binary);
	if (!file.is_open()) 
	{
		return "";
	}
	std::string fileContent;
	char buffer[4096];
	while (file.read(buffer, sizeof(buffer))) 
	{
		fileContent.append(buffer, sizeof(buffer));
	}
	fileContent.append(buffer, file.gcount());
	const size_t keyLen = key.size();
	size_t keyIndex = 0;
	for (string::iterator it = fileContent.begin(); it != fileContent.end(); ++it) 
	{
		*it = static_cast<char>(static_cast<uint8_t>(*it) ^ static_cast<uint8_t>(key[keyIndex]));
		keyIndex = (keyIndex + 1) % keyLen;
	}
	return fileContent;
}

void xortoFile(const string& filePath,const string& key) 
{
	if (key.empty()) 
	{
		return ;
	}
	ifstream file(filePath.c_str(),ios::in | ios::binary);
	if (!file.is_open()) 
	{
		return ; 
	}
	string fileContent;
	char buffer[4096];
	while (file.read(buffer, sizeof(buffer))) 
	{
		fileContent.append(buffer, sizeof(buffer));
	}
	fileContent.append(buffer, file.gcount());
	file.close();
	const size_t keyLen = key.size();
	size_t keyIndex = 0;
	for (std::string::iterator it = fileContent.begin(); it != fileContent.end(); ++it) 
	{
		*it = static_cast<char>(static_cast<uint8_t>(*it) ^ static_cast<uint8_t>(key[keyIndex]));
		keyIndex = (keyIndex + 1) % keyLen;
	}
	std::ofstream outFile(filePath.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
	if (outFile.is_open()) 
	{
		outFile.write(fileContent.data(), fileContent.size());
		outFile.close();
	}
}

void caesarFile(const string& filePath,int shift) 
{
	shift %= 256;
	if (shift < 0) 
	{
		shift += 256;
	}
	std::ifstream file(filePath.c_str(), std::ios::in | std::ios::binary);
	if (!file.is_open()) 
	{
		return ;
	}
	string fileContent;
	char buffer[4096];
	while (file.read(buffer, sizeof(buffer))) 
	{
		fileContent.append(buffer, sizeof(buffer));
	}
	fileContent.append(buffer, file.gcount());
	file.close(); 
	for(string::iterator it = fileContent.begin(); it != fileContent.end();it++) 
	{
		*it = static_cast<char>((static_cast<uint8_t>(*it) + shift) % 256);
	}
	std::ofstream outFile(filePath.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
	if (outFile.is_open()) 
	{
		outFile.write(fileContent.data(), fileContent.size());
		outFile.close();
	}
}
//加
void FileCEnc(const string& filePath, int shift) 
{
	caesarFile(filePath, shift);
}
//解
void FileCDec(const string& filePath, int shift) 
{
	caesarFile(filePath, 256 - (shift % 256)); 
}

//加密
string CEnc(const string& input, int shift) 
{
	shift %= 256;
	if (shift < 0) 
	{
		shift += 256;
	}
	string result = input;
	const size_t len = result.size();
	for (size_t i = 0; i < len; ++i) 
	{
		result[i] = static_cast<char>((static_cast<uint8_t>(result[i]) + shift) % 256);
	}
	return result;
}

//解密
string CDec(const string& input, int shift) 
{
	shift %= 256;
	if (shift < 0) 
	{
		shift += 256;
	}
	return CEnc(input, 256 - shift);
}

void jtbg_h_about()
{
	cout<<"jtbg.h\n";
	cout<<"wroten by @jiaotangbinggan\n";
	cout<<"Process start with 2025/10/4\n";
	cout<<"Lv: 2.0.0 -std11\n";
	cout<<"Used CC BY-NC-ND 4.0\n";
	cout<<"join&talk to me(us):"<<endl;
	cout<<"luogu-1497734"<<endl;
	cout<<"197474286@qq.com"<<endl;
	cout<<"guitu1125@yeah.net"<<endl;
	cout<<"this file hash:none"<<endl;
	cout<<"this file will be new in a long time"<<endl;
	return ;
}
#endif

linux/macOS-Unix

點擊查看代碼
#define _JTBG_UNIX_VERSION "2.0.0(unix-1.0.0) -std=c++11"
#define _JTBG_LICENSE "CC BY-NC-ND 4.0"
// 適配Linux/macOS平台,替換Windows依賴頭文件
#include <bits/stdc++.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/time.h>
#include <ctime>
#include <cstdint>
#include <csignal>
#include <locale>
#include <codecvt>
using namespace std;

// 防止頭文件重複包含
#ifndef _JTBG_UNIX_H_
#define _JTBG_UNIX_H_

// 基礎數學運算宏定義
#define MUL(a,b) (a)*(b)
#define __JTBG_NORETURN(a) ext(a)
#define MUS(a,b) (a)-(b)
#define PLS(a,b) (a)+(b)
#define DEF(a,b) ((b)!=0?(a)/(b):throw invalid_argument("Division by zero"))

// ========================== 1. 哈希計算模塊 ==========================
class MD5 
{
private:
	typedef uint32_t uint32;
	typedef uint64_t uint64;
	struct Context 
	{
		uint32 state[4];
		uint32 count[2];
		unsigned char buffer[64];
	};
	
	static void init(Context &ctx) 
	{
		ctx.count[0] = ctx.count[1] = 0;
		ctx.state[0] = 0x67452301;
		ctx.state[1] = 0xefcdab89;
		ctx.state[2] = 0x98badcfe;
		ctx.state[3] = 0x10325476;
	}
	
	static void update(Context &ctx, const unsigned char *input, size_t length) 
	{
		uint32 i, index, partLen;
		index = (uint32)((ctx.count[0] >> 3) & 0x3F);
		
		if ((ctx.count[0] += ((uint32)length << 3)) < ((uint32)length << 3))
			ctx.count[1]++;
		ctx.count[1] += (uint32)(length >> 29);
		
		partLen = 64 - index;
		if (length >= partLen) {
			memcpy(&ctx.buffer[index], input, partLen);
			transform(ctx.state, ctx.buffer);
			for (i = partLen; i + 63 < length; i += 64)
				transform(ctx.state, &input[i]);
			index = 0;
		} else {
			i = 0;
		}
		memcpy(&ctx.buffer[index], &input[i], length - i);
	}
	
	static void final(unsigned char digest[16], Context &ctx) 
	{
		unsigned char padding[64] = {0x80};
		unsigned char bits[8];
		size_t index, padLen;
		
		encode(bits, ctx.count, 8);
		index = (uint32)((ctx.count[0] >> 3) & 0x3f);
		padLen = (index < 56) ? (56 - index) : (120 - index);
		
		update(ctx, padding, padLen);
		update(ctx, bits, 8);
		encode(digest, ctx.state, 16);
	}
	
	static void transform(uint32 state[4], const unsigned char block[64]) 
	{
		uint32 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
		decode(x, block, 64);
		
#define FF(a,b,c,d,x,s,t) { a += F(b,c,d) + x + t; a = (a << s) | (a >> (32 - s)); a += b; }
#define GG(a,b,c,d,x,s,t) { a += G(b,c,d) + x + t; a = (a << s) | (a >> (32 - s)); a += b; }
#define HH(a,b,c,d,x,s,t) { a += H(b,c,d) + x + t; a = (a << s) | (a >> (32 - s)); a += b; }
#define II(a,b,c,d,x,s,t) { a += I(b,c,d) + x + t; a = (a << s) | (a >> (32 - s)); a += b; }
		
		FF(a,b,c,d,x[0],7,0xd76aa478); FF(d,a,b,c,x[1],12,0xe8c7b756);
		FF(c,d,a,b,x[2],17,0x242070db); FF(b,c,d,a,x[3],22,0xc1bdceee);
		FF(a,b,c,d,x[4],7,0xf57c0faf); FF(d,a,b,c,x[5],12,0x4787c62a);
		FF(c,d,a,b,x[6],17,0xa8304613); FF(b,c,d,a,x[7],22,0xfd469501);
		FF(a,b,c,d,x[8],7,0x698098d8); FF(d,a,b,c,x[9],12,0x8b44f7af);
		FF(c,d,a,b,x[10],17,0xffff5bb1); FF(b,c,d,a,x[11],22,0x895cd7be);
		FF(a,b,c,d,x[12],7,0x6b901122); FF(d,a,b,c,x[13],12,0xfd987193);
		FF(c,d,a,b,x[14],17,0xa679438e); FF(b,c,d,a,x[15],22,0x49b40821);
		
		GG(a,b,c,d,x[1],5,0xf61e2562); GG(d,a,b,c,x[6],9,0xc040b340);
		GG(c,d,a,b,x[11],14,0x265e5a51); GG(b,c,d,a,x[0],20,0xe9b6c7aa);
		GG(a,b,c,d,x[5],5,0xd62f105d); GG(d,a,b,c,x[10],9,0x02441453);
		GG(c,d,a,b,x[15],14,0xd8a1e681); GG(b,c,d,a,x[4],20,0xe7d3fbc8);
		GG(a,b,c,d,x[9],5,0x21e1cde6); GG(d,a,b,c,x[14],9,0xc33707d6);
		GG(c,d,a,b,x[3],14,0xf4d50d87); GG(b,c,d,a,x[8],20,0x455a14ed);
		GG(a,b,c,d,x[13],5,0xa9e3e905); GG(d,a,b,c,x[2],9,0xfcefa3f8);
		GG(c,d,a,b,x[7],14,0x676f02d9); GG(b,c,d,a,x[12],20,0x8d2a4c8a);
		
		HH(a,b,c,d,x[5],4,0xfffa3942); HH(d,a,b,c,x[8],11,0x8771f681);
		HH(c,d,a,b,x[11],16,0x6d9d6122); HH(b,c,d,a,x[14],23,0xfde5380c);
		HH(a,b,c,d,x[1],4,0xa4beea44); HH(d,a,b,c,x[4],11,0x4bdecfa9);
		HH(c,d,a,b,x[7],16,0xf6bb4b60); HH(b,c,d,a,x[10],23,0xbebfbc70);
		HH(a,b,c,d,x[13],4,0x289b7ec6); HH(d,a,b,c,x[0],11,0xeaa127fa);
		HH(c,d,a,b,x[3],16,0xd4ef3085); HH(b,c,d,a,x[6],23,0x04881d05);
		HH(a,b,c,d,x[9],4,0xd9d4d039); HH(d,a,b,c,x[12],11,0xe6db99e5);
		HH(c,d,a,b,x[15],16,0x1fa27cf8); HH(b,c,d,a,x[2],23,0xc4ac5665);
		
		II(a,b,c,d,x[0],6,0xf4292244); II(d,a,b,c,x[7],10,0x432aff97);
		II(c,d,a,b,x[14],15,0xab9423a7); II(b,c,d,a,x[5],21,0xfc93a039);
		II(a,b,c,d,x[12],6,0x655b59c3); II(d,a,b,c,x[3],10,0x8f0ccc92);
		II(c,d,a,b,x[10],15,0xffeff47d); II(b,c,d,a,x[1],21,0x85845dd1);
		II(a,b,c,d,x[8],6,0x6fa87e4f); II(d,a,b,c,x[15],10,0xfe2ce6e0);
		II(c,d,a,b,x[6],15,0xa3014314); II(b,c,d,a,x[13],21,0x4e0811a1);
		II(a,b,c,d,x[4],6,0xf7537e82); II(d,a,b,c,x[11],10,0xbd3af235);
		II(c,d,a,b,x[2],15,0x2ad7d2bb); II(b,c,d,a,x[9],21,0xeb86d391);
		
#undef FF
#undef GG
#undef HH
#undef II
		
		state[0] += a;
		state[1] += b;
		state[2] += c;
		state[3] += d;
	}
	
	static inline uint32 F(uint32 x, uint32 y, uint32 z) { return (x & y) | (~x & z); }
	static inline uint32 G(uint32 x, uint32 y, uint32 z) { return (x & z) | (y & ~z); }
	static inline uint32 H(uint32 x, uint32 y, uint32 z) { return x ^ y ^ z; }
	static inline uint32 I(uint32 x, uint32 y, uint32 z) { return y ^ (x | ~z); }
	
	static void encode(unsigned char *output, const uint32 *input, size_t length) 
	{
		for (size_t i = 0, j = 0; j < length; i++, j += 4) 
		{
			output[j] = (unsigned char)(input[i] & 0xFF);
			output[j + 1] = (unsigned char)((input[i] >> 8) & 0xFF);
			output[j + 2] = (unsigned char)((input[i] >> 16) & 0xFF);
			output[j + 3] = (unsigned char)((input[i] >> 24) & 0xFF);
		}
	}
	
	static void decode(uint32 *output, const unsigned char *input, size_t length) 
	{
		for (size_t i = 0, j = 0; j < length; i++, j += 4)
			output[i] = ((uint32)input[j]) | (((uint32)input[j + 1]) << 8) |
			(((uint32)input[j + 2]) << 16) | (((uint32)input[j + 3]) << 24);
	}
	
public:
	static string hash(const string &input) 
	{
		Context ctx;
		init(ctx);
		update(ctx, (const unsigned char*)input.c_str(), input.length());
		
		unsigned char digest[16];
		final(digest, ctx);
		
		char hex_str[33];
		for (int i = 0; i < 16; i++)
			snprintf(hex_str + i * 2, 3, "%02x", digest[i]);
		hex_str[32] = '\0';
		
		return string(hex_str);
	}
};

// 字符串哈希(多項式哈希)
unsigned long long pHash(const string& s) 
{
	const unsigned long long base = 911382629ULL;
	const unsigned long long mod = 1000000000000000003ULL;
	unsigned long long hashValue = 0;
	
	for (size_t i = 0; i < s.size(); ++i) 
	{
		char c = s[i];
		hashValue = (hashValue * base + static_cast<unsigned long long>(c)) % mod;
	}
	
	return hashValue;
}

// 前綴哈希(支持子串哈希計算)
struct StringHash 
{
	static const unsigned long long base = 911382629ULL;
	static const unsigned long long mod = 1000000000000000003ULL;
	vector<unsigned long long> hash;
	vector<unsigned long long> power;
	
	StringHash(const string& s) 
	{
		int n = s.size();
		hash.resize(n + 1);
		power.resize(n + 1);
		power[0] = 1;
		
		for (int i = 0; i < n; ++i) {
			hash[i+1] = (hash[i] * base + static_cast<unsigned long long>(s[i])) % mod;
			power[i+1] = (power[i] * base) % mod;
		}
	}
	
	// 獲取子串s[l..r]的哈希值(0-based,包含l和r)
	unsigned long long getHash(int l, int r) 
	{
		if (l > r || l < 0 || r >= (int)hash.size()-1)
			throw invalid_argument("Invalid substring range");
		
		int len = r - l + 1;
		unsigned long long res = (hash[r+1] - hash[l] * power[len]) % mod;
		return res < 0 ? res + mod : res;
	}
};

// 基礎字符串哈希(31為基數)
size_t Hash(const string& s) 
{
	size_t hashVal = 0;
	for (size_t i = 0; i < s.size(); ++i) 
	{
		hashVal = hashVal * 31 + static_cast<size_t>(s[i]);
	}
	return hashVal;
}

// ========================== 2. 文件操作模塊 ==========================
struct Save
{
	string path;
	int errorlevel = -1;  // 1100:讀失敗, 1000:寫失敗
	ifstream save_i;
	ofstream save_o;
	
	// 設置文件路徑
	void setpt(const string& s) { path = s; }
	
	// 文本方式讀取(無鎖)
	void read_nol() 
	{
		save_i.open(path.c_str());
		if (!save_i.good()) 
			errorlevel = 1100;
	}
	
	// 二進制方式讀取
	void read_bin() 
	{
		save_i.open(path.c_str(), ios::in | ios::binary);
		if (!save_i.good()) 
			errorlevel = 1100;
	}
	
	// 文本方式寫入(覆蓋)
	void save_nol() 
	{
		save_o.open(path.c_str());
		if (!save_o.good()) 
			errorlevel = 1000;
	}
	
	// 文本方式追加寫入
	void save_app() 
	{
		save_o.open(path.c_str(), ios::app | ios::out);
		if (!save_o.good()) 
			errorlevel = 1000;
	}
	
	// 二進制方式寫入(覆蓋)
	void save_bin() 
	{
		save_o.open(path.c_str(), ios::binary | ios::out);
		if (!save_o.good()) 
			errorlevel = 1000;
	}
	
	// 關閉寫入流
	void save_stop() { save_o.close(); }
	
	// 關閉讀取流
	void read_stop() { save_i.close(); }
};

// 計算文件MD5值
string FileMD5(const string& path)
{
	ifstream file(path, ios::in | ios::binary);
	if (!file.is_open()) 
		return "";
	
	string fileContent;
	file.seekg(0, ios::end);
	size_t fileSize = static_cast<size_t>(file.tellg());
	file.seekg(0, ios::beg);
	
	fileContent.reserve(fileSize);
	fileContent.assign(istreambuf_iterator<char>(file), istreambuf_iterator<char>());
	
	if (!file && !file.eof()) 
		return "";
	
	return MD5::hash(fileContent);
}

// 獲取文件大小(字節)
long long getFileSize(const string& filename)
{
	struct stat fileStat;
	if (stat(filename.c_str(), &fileStat) != 0)
		return -1;
	return static_cast<long long>(fileStat.st_size);
}

// 檢查文件是否可讀寫
bool fileok(const string& filename) 
{
	ifstream file(filename);
	return file.good();
}

// 統計文件夾內文件數量(僅一級目錄,不包含子文件夾)
int getFileCountInDir(const string& dirPath) 
{
	DIR* dir = opendir(dirPath.c_str());
	if (dir == nullptr)
		return -1;
	
	int count = 0;
	struct dirent* entry;
	while ((entry = readdir(dir)) != nullptr) 
	{
		// 跳過.和..目錄
		if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
			continue;
		
		// 判斷是否為文件(非目錄)
		string fullPath = dirPath + "/" + entry->d_name;
		struct stat statBuf;
		if (stat(fullPath.c_str(), &statBuf) == 0 && S_ISREG(statBuf.st_mode))
			count++;
	}
	
	closedir(dir);
	return count;
}

// ========================== 3. 控制枱控制模塊 ==========================
// 控制枱顏色枚舉(ANSI轉義碼對應)
enum Color 
{
	BLACK = 30,      // 前景色:黑
	RED = 31,        // 前景色:紅
	GREEN = 32,      // 前景色:綠
	YELLOW = 33,     // 前景色:黃
	BLUE = 34,       // 前景色:藍
	MAGENTA = 35,    // 前景色:品紅
	CYAN = 36,       // 前景色:青
	WHITE = 37,      // 前景色:白
	BRIGHT_BLACK = 90,   // 亮前景:黑
	BRIGHT_RED = 91,     // 亮前景:紅
	BRIGHT_GREEN = 92,   // 亮前景:綠
	BRIGHT_YELLOW = 93,  // 亮前景:黃
	BRIGHT_BLUE = 94,    // 亮前景:藍
	BRIGHT_MAGENTA = 95, // 亮前景:品紅
	BRIGHT_CYAN = 96,    // 亮前景:青
	BRIGHT_WHITE = 97,   // 亮前景:白
	// 背景色(+40)
	BG_BLACK = 40,
	BG_RED = 41,
	BG_GREEN = 42,
	BG_YELLOW = 43,
	BG_BLUE = 44,
	BG_MAGENTA = 45,
	BG_CYAN = 46,
	BG_WHITE = 47,
	BG_BRIGHT_BLACK = 100,
	BG_BRIGHT_RED = 101,
	BG_BRIGHT_GREEN = 102,
	BG_BRIGHT_YELLOW = 103,
	BG_BRIGHT_BLUE = 104,
	BG_BRIGHT_MAGENTA = 105,
	BG_BRIGHT_CYAN = 106,
	BG_BRIGHT_WHITE = 107
};

// 設置控制枱文本顏色(前景色+背景色)
void scg(Color fg, Color bg)
{
	cout << "\033[" << static_cast<int>(fg) << ";" << static_cast<int>(bg) << "m";
}

// 重置控制枱顏色為默認
void set_back_color()
{
	cout << "\033[0m"; // ANSI重置碼
}

// 獲取控制枱尺寸(寬x高,單位:字符)
void getCSize(int &width, int &height) 
{
	struct winsize w;
	ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
	width = w.ws_col;
	height = w.ws_row;
}

// 設置控制枱光標位置(x:列,y:行,0-based)
void setcursor(int x, int y) 
{
	cout << "\033[" << (y + 1) << ";" << (x + 1) << "H"; // ANSI光標定位碼(1-based)
}

// 隱藏/顯示控制枱光標
void setCVis(bool visible) 
{
	if (visible)
		cout << "\033[?25h"; // 顯示光標
	else
		cout << "\033[?25l"; // 隱藏光標
}

// 清除控制枱指定區域內容(x:起始列,y:起始行,width:寬度,height:高度)
void clearCA(int x, int y, int width, int height) 
{
	for (int i = 0; i < height; ++i) 
	{
		setcursor(x, y + i);
		cout << string(width, ' ');
	}
	setcursor(x, y); // 回到起始位置
}

// 清除整個控制枱
void syst() 
{
	cout << "\033[2J\033[H"; // ANSI清屏+光標歸位
}

// ========================== 4. 時間與定時器模塊 ==========================
// 時間類型枚舉
enum TimeType
{
	yer = 0,  // 年份
	mon = 1,  // 月份(1-12)
	dat = 2,  // 日期(1-31)
	hor = 3,  // 小時(0-23)
	mit = 4,  // 分鐘(0-59)
	sec = 5,  // 秒(0-59)
	mst = 6   // 毫秒(0-999)
};

// 獲取指定類型的時間(支持枚舉參數)
int Gettime(TimeType x)
{
	time_t now = time(nullptr);
	tm *localTime = localtime(&now);
	
	switch (x)
	{
		case yer: return 1900 + localTime->tm_year;
		case mon: return 1 + localTime->tm_mon;
		case dat: return localTime->tm_mday;
		case hor: return localTime->tm_hour;
		case mit: return localTime->tm_min;
		case sec: return localTime->tm_sec;
		case mst: 
		{
			struct timeval tv;
			gettimeofday(&tv, nullptr);
			return tv.tv_usec / 1000; // 微秒轉毫秒
		}
		default: return -1;
	}
}

// 獲取指定類型的時間(支持字符串參數)
int Gettime(const string& x)
{
	if (x == "year") return Gettime(yer);
	if (x == "mon")  return Gettime(mon);
	if (x == "dat")  return Gettime(dat);
	if (x == "hor")  return Gettime(hor);
	if (x == "mit")  return Gettime(mit);
	if (x == "sec")  return Gettime(sec);
	if (x == "mst")  return Gettime(mst);
	return -1;
}

// 高精度定時器
struct Timer
{
private:
	using Clock = chrono::high_resolution_clock;
	using TimePoint = chrono::time_point<Clock>;
	
	TimePoint start_;
	TimePoint pause_;
	bool isRunning_;
	chrono::duration<double> elapsed_;
	
public:
	Timer() : isRunning_(false), elapsed_(0) {}
	
	// 開始計時
	void starttick() 
	{
		if (!isRunning_) 
		{
			start_ = Clock::now();
			isRunning_ = true;
		}
	}
	
	// 暫停計時
	void pausetick() 
	{
		if (isRunning_) 
		{
			pause_ = Clock::now();
			elapsed_ += pause_ - start_;
			isRunning_ = false;
		}
	}
	
	// 重置計時
	void resettick() 
	{
		isRunning_ = false;
		elapsed_ = chrono::duration<double>(0);
	}
	
	// 獲取已流逝時間(秒)
	double timesec() const 
	{
		if (isRunning_) 
		{
			auto now = Clock::now();
			return (elapsed_ + (now - start_)).count();
		}
		return elapsed_.count();
	}
	
	// 獲取已流逝時間(毫秒)
	double timemst() const 
	{
		return timesec() * 1000.0;
	}
};

// 延遲函數(毫秒,高精度)
void msSleep(int milliseconds) 
{
	this_thread::sleep_for(chrono::milliseconds(milliseconds));
}

// 獲取當前時間戳(秒級)
time_t time_now() 
{
	return time(nullptr);
}

// 獲取當前時間戳(毫秒級)
long long getms() 
{
	struct timeval tv;
	gettimeofday(&tv, nullptr);
	return (long long)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

// ========================== 5. 數據加密與編碼模塊 ==========================
// XOR字符串加解密(密鑰循環複用)
string xorpass(const string &str, const string &key) 
{
	if (key.empty()) return str;
	
	string result = str;
	size_t keyLen = key.size();
	for (size_t i = 0; i < result.size(); ++i)
	{
		result[i] ^= key[i % keyLen];
	}
	return result;
}

// XOR文件加解密(返回加密後內容)
string xorFile(const string& filePath, const string& key) 
{
	if (key.empty()) return "";
	
	int fd = open(filePath.c_str(), O_RDONLY | O_BINARY);
	if (fd == -1) return "";
	
	struct stat st;
	fstat(fd, &st);
	size_t fileSize = st.st_size;
	string fileContent(fileSize, 0);
	read(fd, &fileContent[0], fileSize);
	close(fd);
	
	const size_t keyLen = key.size();
	size_t keyIndex = 0;
	for (auto& c : fileContent) 
	{
		c = static_cast<char>(static_cast<uint8_t>(c) ^ static_cast<uint8_t>(key[keyIndex]));
		keyIndex = (keyIndex + 1) % keyLen;
	}
	
	return fileContent;
}

// XOR文件加解密(直接寫入原文件)
void xortoFile(const string& filePath, const string& key) 
{
	if (key.empty()) return;
	
	int fd = open(filePath.c_str(), O_RDWR | O_BINARY);
	if (fd == -1) return;
	
	struct stat st;
	fstat(fd, &st);
	size_t fileSize = st.st_size;
	string fileContent(fileSize, 0);
	read(fd, &fileContent[0], fileSize);
	
	const size_t keyLen = key.size();
	size_t keyIndex = 0;
	for (auto& c : fileContent) 
	{
		c = static_cast<char>(static_cast<uint8_t>(c) ^ static_cast<uint8_t>(key[keyIndex]));
		keyIndex = (keyIndex + 1) % keyLen;
	}
	
	lseek(fd, 0, SEEK_SET);
	write(fd, &fileContent[0], fileSize);
	close(fd);
}

// 凱撒文件加解密(移位加密)
void caesarFile(const string& filePath, int shift) 
{
	shift %= 256;
	if (shift < 0) shift += 256;
	
	int fd = open(filePath.c_str(), O_RDWR | O_BINARY);
	if (fd == -1) return;
	
	struct stat st;
	fstat(fd, &st);
	size_t fileSize = st.st_size;
	string fileContent(fileSize, 0);
	read(fd, &fileContent[0], fileSize);
	
	for (auto& c : fileContent) 
	{
		c = static_cast<char>((static_cast<uint8_t>(c) + shift) % 256);
	}
	
	lseek(fd, 0, SEEK_SET);
	write(fd, &fileContent[0], fileSize);
	close(fd);
}

// 凱撒加密(字符串)
string CEnc(const string& input, int shift) 
{
	shift %= 256;
	if (shift < 0) shift += 256;
	
	string result = input;
	for (auto& c : result) 
	{
		c = static_cast<char>((static_cast<uint8_t>(c) + shift) % 256);
	}
	return result;
}

// 凱撒解密(字符串)
string CDec(const string& input, int shift) 
{
	shift %= 256;
	if (shift < 0) shift += 256;
	return CEnc(input, 256 - shift);
}

// 文件凱撒加密
void FileCEnc(const string& filePath, int shift) 
{
	caesarFile(filePath, shift);
}

// 文件凱撒解密
void FileCDec(const string& filePath, int shift) 
{
	caesarFile(filePath, 256 - (shift % 256));
}

// Base64編碼
string base64up(const string &str, const string &base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") 
{
	string result;
	int val = 0, valBits = 0;
	
	for (unsigned char c : str) 
	{
		val = (val << 8) + c;
		valBits += 8;
		while (valBits >= 6)
		{
			result += base64Chars[(val >> (valBits - 6)) & 0x3F];
			valBits -= 6;
		}
	}
	
	if (valBits > 0) 
	{
		val <<= (6 - valBits);
		result += base64Chars[val & 0x3F];
	}
	
	while (result.size() % 4 != 0) 
	{
		result += '=';
	}
	
	return result;
}

// Base64解碼
string base64dec(const string &str, const string base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") 
{
	string result;
	vector<int> val(4, -1); 
	
	for (size_t i = 0; i < str.size(); ++i) 
	{
		char c = str[i];
		if (c == '=') break;
		
		size_t pos = base64Chars.find(c);
		if (pos == string::npos) continue;
		
		val[i % 4] = pos;
		if (i % 4 == 3) 
		{
			result += (val[0] << 2) + ((val[1] >> 4) & 0x3);
			if (val[2] != -1) 
			{
				result += ((val[1] << 4) & 0xF0) + ((val[2] >> 2) & 0xF);
			}
			if (val[3] != -1) 
			{
				result += ((val[2] << 6) & 0xC0) + val[3];
			}
			val.assign(4, -1);
		}
	}
	
	return result;
}

// ========================== 6. 數學計算模塊 ==========================
#ifndef _NOMATH_
#define _NOMATH_

// 數學常量(高精度)
constexpr double PI = 3.14159265358979323846264338327950288419716939937510582097494459;
constexpr double E = 2.718281828459045235360287471352662497757247093699959574966967628;
constexpr double SQRT2 = 1.414213562373095048801688724209698078569671875376948073176679738;
constexpr double DEG_TO_RAD = PI / 180.0;  // 角度轉弧度係數
constexpr double RAD_TO_DEG = 180.0 / PI;  // 弧度轉角度係數

// 角度轉弧度
inline double toRadians(double degrees) 
{
	return degrees * DEG_TO_RAD;
}

// 弧度轉角度
inline double toDegrees(double radians) 
{
	return radians * RAD_TO_DEG;
}

// 計算階乘(n<0返回-1,溢出返回-1)
inline long long fac(int n) 
{
	if (n < 0) return -1;
	if (n == 0 || n == 1) return 1;
	
	long long result = 1;
	for (int i = 2; i <= n; ++i) 
	{
		if (result > LLONG_MAX / i)  // 防止溢出
			return -1;
		result *= i;
	}
	return result;
}

// 快速冪(支持負指數)
double qpow(double base, int exponent) 
{
	if (exponent == 0) return 1.0;
	if (base == 0.0) return 0.0;
	
	bool isNegative = exponent < 0;
	unsigned int absExponent = static_cast<unsigned int>(isNegative ? -exponent : exponent);
	
	double result = 1.0;
	double current = base;
	while (absExponent > 0) 
	{
		if (absExponent % 2 == 1) 
			result *= current;
		current *= current;   
		absExponent /= 2;       
	}
	
	return isNegative ? 1.0 / result : result;
}

// 排列數計算(A(a,b) = a!/(a-b)!,非法輸入返回-1)
long long A(int a, int b) 
{
	if (a < 0 || b < 0 || a < b) return -1;
	if (b == 0) return 1;
	
	long long result = 1;
	for (int i = 0; i < b; ++i) 
	{
		if (result > LLONG_MAX / (a - i))  // 防止溢出
			return -1;
		result *= (a - i);
	}
	return result;
}

// 組合數計算(C(a,b) = a!/(b!(a-b)!),非法輸入返回-1)
long long C(int a, int b)
{
	if (a < 0 || b < 0 || a < b) return -1;
	if (b == 0 || a == b) return 1;
	
	// 優化:C(a,b) = C(a,a-b),取較小值減少計算
	b = min(b, a - b);
	long long result = 1;
	for (int i = 1; i <= b; ++i) 
	{
		// 防止溢出:先乘後除(確保整除)
		if (result > LLONG_MAX / (a - b + i))
			return -1;
		result = result * (a - b + i) / i;
	}
	return result;
}

// 判斷素數(優化版:遍歷至sqrt(x))
bool isHe(int x)
{
	if (x <= 1) return false;
	if (x == 2 || x == 3) return true;
	if (x % 2 == 0 || x % 3 == 0) return false;
	
	for (int i = 5; i * i <= x; i += 6) 
	{
		if (x % i == 0 || x % (i + 2) == 0)
			return false;
	}
	return true;
}

#endif // _NOMATH_

// ========================== 7. 字符串處理模塊 ==========================
// 字符串轉為全小寫
void lowerstring(string &s)
{
	for (auto& c : s) 
	{
		if (c >= 'A' && c <= 'Z')
			c += ('a' - 'A');
	}
}

// 字符串轉為全大寫
void uperstring(string &s)
{
	for (auto& c : s) 
	{
		if (c >= 'a' && c <= 'z')
			c -= ('a' - 'A');
	}
}

// 字符串首字母大寫,其餘小寫
void Testsuper(string &s) 
{
	if (s.empty()) return;
	
	s[0] = toupper(s[0]);
	for (size_t i = 1; i < s.size(); ++i) 
	{
		s[i] = tolower(s[i]);
	}
}

// 清除輸入緩衝區
void flushed() 
{
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	cin.clear();
}

// 檢查字符串是否為數字(支持整數和小數,可帶正負號)
bool isNumber(const string& str) 
{
	if (str.empty()) return false;
	
	size_t start = 0;
	if (str[0] == '+' || str[0] == '-') 
		start = 1;
	
	bool hasDot = false;
	for (size_t i = start; i < str.size(); ++i) 
	{
		if (str[i] == '.') 
		{
			if (hasDot) return false;  // 只能有一個小數點
			hasDot = true;
		}
		else if (!isdigit(str[i])) 
		{
			return false;
		}
	}
	
	// 避免單獨的符號或小數點(如"+"、"."、"-.")
	return (start < str.size()) && !(start == 1 && str.size() == 1) && !(hasDot && start == str.size() - 1);
}

// 任意類型轉為字符串(基於stringstream)
template <typename to_string_T>
string tostring(to_string_T k)
{
	stringstream ans;
	ans << k;
	return ans.str();
}

// ========================== 8. 隨機數模塊 ==========================
// 生成指定區間整數隨機數([a,b])
int rd(int a, int b)
{
	if (a > b) swap(a, b);
	// 基於當前時間初始化隨機種子(避免多次調用導致重複)
	static bool seeded = false;
	if (!seeded) 
	{
		srand(static_cast<unsigned int>(time(nullptr)) ^ getpid());
		seeded = true;
	}
	return a + (rand() % (b - a + 1));
}

// 生成指定區間浮點數隨機數([min,max])
double random(double min, double max) 
{
	if (min > max) swap(min, max);
	static bool seeded = false;
	if (!seeded) 
	{
		srand(static_cast<unsigned int>(time(nullptr)) ^ getpid());
		seeded = true;
	}
	return min + (max - min) * (static_cast<double>(rand()) / RAND_MAX);
}

// 生成指定長度的隨機字符串(包含數字和大小寫字母)
string randS(int length) 
{
	if (length <= 0) return "";
	
	const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	string result;
	result.reserve(length);
	
	static bool seeded = false;
	if (!seeded) 
	{
		srand(static_cast<unsigned int>(time(nullptr)) ^ getpid());
		seeded = true;
	}
	
	for (int i = 0; i < length; ++i) 
	{
		result += chars[rand() % chars.size()];
	}
	return result;
}

// ========================== 9. 日誌模塊 ==========================
struct logger
{
	Save rep;
	enum error_type
	{
		error = 0,   // 錯誤
		info = 1,    // 信息
		warn = 2,    // 警告
		debug = 3    // 調試
	};
	
	// 初始化日誌文件(覆蓋原有內容)
	void reset_logger(const string& path)
	{
		rep.setpt(path);
		rep.save_nol();
		if (rep.errorlevel != 1000) 
		{
			rep.save_o << "[" << Gettime(yer) << "/" << Gettime(mon) << "/" << Gettime(dat) 
			<< "-" << Gettime(hor) << ":" << Gettime(mit) << ":" << Gettime(sec) << "] "
			<< "Logger initialized" << endl;
		}
	}
	
	// 寫入日誌
	void report(const string& s, error_type tp)
	{
		if (!rep.save_o.good()) return;
		
		// 時間戳(精確到毫秒)
		rep.save_o << "[" << Gettime(hor) << ":" << Gettime(mit) << ":" << Gettime(sec) 
		<< "(" << Gettime(mst) << ")] ";
		
		// 日誌類型
		switch (tp)
		{
			case error: rep.save_o << "{type=error} "; break;
			case info:  rep.save_o << "{type=info} ";  break;
			case warn:  rep.save_o << "{type=warn} ";  break;
			case debug: rep.save_o << "{type=debug} "; break;
			default:    rep.save_o << "{type=unknow} ";
		}
		
		// 日誌內容
		rep.save_o << s << endl;
		rep.save_o.flush();  // 強制刷新緩衝區
	}
	
	// 關閉日誌文件
	void stop()
	{
		if (rep.save_o.good()) 
		{
			rep.save_o << "[" << Gettime(hor) << ":" << Gettime(mit) << ":" << Gettime(sec) 
			<< "] Logger stopped" << endl;
		}
		rep.save_stop();
	}
};

// ========================== 10. 系統操作與輔助模塊 ==========================
// 執行系統命令
void sys(const string& cmd) 
{
	system(cmd.c_str());
}

// 無提示暫停(等待按鍵)
void no_pause() 
{
	cout << "\033[?25h"; // 顯示光標
	cout << "Press any key to continue...";
	flushed();
	getchar();
	cout << "\033[?25l"; // 隱藏光標
}

// 標準暫停(帶提示)
void pause() 
{
	system("read -n 1 -s -r -p \"Press any key to continue...\"");
	cout << endl;
}

// 類型轉換快捷宏
#define to_int(x) stoi(x)
#define to_long(x) stol(x)
#define to_double(x) stod(x)
#define to_str(x) tostring(x)
#define sleep(ms) msSleep(ms)

// 進程退出(帶提示)
int ext(int num)
{
	cout << "[jtbgunix.h] Process exited with return value " << num << endl;
	exit(num);
	return num;
}

// 內存單位轉換結構體
struct memory
{
	long long bytes;
	
	double toB()    { return static_cast<double>(bytes); }
	double toKB()   { return bytes / 1024.0; }
	double toMB()   { return bytes / (1024.0 * 1024.0); }
	double toGB()   { return bytes / (1024.0 * 1024.0 * 1024.0); }
	double toTB()   { return bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0); }
	double toPB()   { return bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0); }
};

// 內存單位轉換全局函數
double rtoB(int bytes)    { return static_cast<double>(bytes); }
double rtoKB(int bytes)   { return bytes / 1024.0; }
double rtoMB(int bytes)   { return bytes / (1024.0 * 1024.0); }
double rtoGB(int bytes)   { return bytes / (1024.0 * 1024.0 * 1024.0); }
double rtoTB(int bytes)   { return bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0); }
double rtoPB(int bytes)   { return bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0); }

// 按字符延遲輸出字符串
void say(const string& s, int t)
{
	if (t < 0) return;
	for (char c : s) 
	{
		cout << c << flush;
		msSleep(t);
	}
}

// 頭文件信息
void jtbgunix_h_about()
{
	cout << "jtbgunix.h\n";
	cout << "Written by @jiaotangbinggan\n";
	cout << "Process started with 2025/10/4\n";
	cout << "Version: " << _JTBG_UNIX_VERSION << "\n";
	cout << "License: " << _JTBG_LICENSE << "\n";
	cout << "Contact:\n";
	cout << "  Luogu: luogu-1497734\n";
	cout << "  Email: 197474286@qq.com, guitu1125@yeah.net\n";
	cout << "This file hash: none\n";
}

// 關於信息快捷宏
#define about() jtbgunix_h_about()

#endif // _JTBG_UNIX_H_

Add a new Comments

Some HTML is okay.