[{"content":"Normally, to capture information about the call site when printing a log, the traditional approach is to define a macro that collects that information.\nBut with C++20\u0026rsquo;s std::source_location we can write a logging function that needs no macro at all.\ncpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 #include \u0026lt;iostream\u0026gt; #include \u0026lt;format\u0026gt; #include \u0026lt;source_location\u0026gt; #include \u0026lt;string_view\u0026gt; namespace Logger { struct FormatWithLocation { std::string_view value; std::source_location loc; template \u0026lt;typename String\u0026gt; FormatWithLocation(const String\u0026amp; s, const std::source_location\u0026amp; l = std::source_location::current()) : value{s}, loc{l} {} }; template \u0026lt;typename... Args\u0026gt; void Debug(FormatWithLocation fmt, Args \u0026amp;\u0026amp;...args) { std::string formattedMessage = std::vformat(fmt.value, std::make_format_args(std::forward\u0026lt;Args\u0026gt;(args)...)); std::cout \u0026lt;\u0026lt; \u0026#34;[\u0026#34; \u0026lt;\u0026lt; fmt.loc.file_name() \u0026lt;\u0026lt; \u0026#34;:\u0026#34; \u0026lt;\u0026lt; fmt.loc.line() \u0026lt;\u0026lt; \u0026#34;] \u0026#34; \u0026lt;\u0026lt; formattedMessage \u0026lt;\u0026lt; std::endl; } } // namespace Logger int main() { int num = 123; Logger::Debug(\u0026#34;test {}\u0026#34;, num); return 0; } Compile and run:\nbash 1 g++ main.cc -Wall -o main \u0026amp;\u0026amp; ./main Expected output:\nbash 1 [main.cc:30] test 123 ","date":"2026-04-15T13:17:18+08:00","permalink":"https://boiltask.com/en/knowledge/cpp/log-without-macro/","title":"Logging in C++20 Without a Macro"},{"content":"I have been watching Godot for a long time — the first try was back when Brotato took off, though I only scratched the surface.\nWith Godot doing better and better lately, I want to look into it more seriously.\nDownload and install Godot is an open-source engine, so documentation and resources are easy to find, and there is even an official Steam release.\nIf you do not need to build from source, installing through Steam is enough.\nGodot Engine Official documentation Reading the official docs from start to finish is basically enough to get a working understanding of Godot.\nGodot Engine documentation Programming language Godot ships its own language, GDScript, but the syntax is essentially identical to Python. I am not a fan of expressing nesting with indentation, but I can live with it (far more convenient than wiring complex logic together in blueprints, anyway).\nOne genuinely nice touch: the team provides a language tutorial built with the engine itself and exported to the web.\nLearn to Code From Zero with Godot It is quite fun overall — you can even play it as a programming game.\nSample projects There are plenty of sample projects; you can browse them in Godot\u0026rsquo;s project manager when it starts.\n","date":"2026-04-09T12:33:18+08:00","permalink":"https://boiltask.com/en/knowledge/godot/first-look/","title":"A First Look at Godot"},{"content":"Exercise: Maps Implement WordCount. It should return a map of the counts of each \u0026ldquo;word\u0026rdquo; in the string s. The wc.Test function runs a sequence of test cases against it and reports pass or fail.\nYou will find strings.Fields helpful.\nReference code:\nGo 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package main import ( \u0026#34;golang.org/x/tour/wc\u0026#34; \u0026#34;strings\u0026#34; ) func WordCount(s string) map[string]int { stringList := strings.Fields(s) res := make(map[string]int) for _, word := range stringList { res[word]++ } return res } func main() { wc.Test(WordCount) } ","date":"2021-09-01T00:40:23+08:00","permalink":"https://boiltask.com/en/knowledge/golang-map/","title":"[Go Tour] Exercise: Maps"},{"content":"Applying static to ordinary variables It changes the variable\u0026rsquo;s storage area and lifetime: the variable lives in static storage, its space is allocated before main runs, and it is initialised with the given initial value — or with the default value if none is given.\nAn ordinary variable gets space on the stack when execution reaches its definition, and that space is released when the function returns. Marking it static lets the value inside the function survive until the next call.\nA static local variable is initialised only once, and its lifetime is extended until the program ends.\ncpp 1 2 3 4 5 6 7 8 9 10 11 12 #include \u0026lt;iostream\u0026gt; using namespace std; void staticLocalVar() { static int a = 0; // initialised once at run time; later calls skip the initialisation cout \u0026lt;\u0026lt; \u0026#34;a=\u0026#34; \u0026lt;\u0026lt; a \u0026lt;\u0026lt; endl; ++a; } int main() { staticLocalVar(); // first call, prints a=0 staticLocalVar(); // second call, remembers the value left by the first call, prints a=1 return 0; } Applying static to ordinary functions It limits the function\u0026rsquo;s scope: the function can only be used inside the file that defines it. In a project with several people, static keeps your helper from colliding with a same-named function in someone else\u0026rsquo;s namespace.\nApplying static to member variables It makes every object share one copy of the variable, and the member can be accessed without creating an object.\nC++ needs a data object that serves the whole class; that is what a static data member is for.\nIf every object of a class needs a value, marking it static means you change the value once and all objects see the new value.\nApplying static to member functions It lets the function be called without creating an object, but a static member function cannot access non-static members.\nstatic and const static const is equivalent to const static; for member variables, read the two together.\nA member function cannot be both const and static — the two meanings contradict each other.\n","date":"2020-03-23T05:30:15Z","permalink":"https://boiltask.com/en/knowledge/cpp/static/","title":"The static Keyword in C++ — A Summary"},{"content":" There are n items; the i-th item (i = 1, 2, 3…n) has value vi and weight wi. We have a knapsack that can carry at most m. We pick some items to put in it, at most one of each, and obviously the total weight must not exceed m. We want the total value to be as large as possible — so which items do we pick? Assume every number involved is a positive integer.\nIf you have not thought the knapsack problem through carefully, the first instinct tends to be greedy.\nSort by how valuable an item is, for example, and take the valuable ones first.\nBut consider this data:\nn = 3, m = 3\nv = (2, 2, 3)\nw = (1, 2, 3)\nThe \u0026ldquo;most valuable first\u0026rdquo; strategy takes the item worth 3 and the knapsack is full — yet if we take the first two items the total value reaches 4.\nSort by value for weight instead: For this data\nn = 3, m = 7\nv = (2, 3, 4)\nw = (3, 4, 5)\nSince 2/3 \u0026lt; 3/4 \u0026lt; 4/5, we take the third item first — and once it is in, nothing else fits! Total value 4, while the first two items would have given 5.\nThe reason is that greedy assumes the global optimum can be built out of each step\u0026rsquo;s local optimum, whereas in the knapsack problem whether taking a step is optimal depends on the whole — that is, it is \u0026ldquo;dynamic\u0026rdquo;. Which is why the knapsack problem is a canonical dynamic-programming problem.\nNow look at a fractional knapsack problem:\nA traveller has a knapsack that can carry at most m kilograms, and there are n items whose weight and value are w[i] and c[i]. What is the maximum value the traveller can get?\nThis one is a greedy problem: keep taking the best value-for-weight until the bag is full. So whether greedy works comes down to whether an item may be taken partially.\nThe knapsack problem then spawns many variants, and the DP formulations differ, so it takes practice to get comfortable with this whole family of problems.\nReference:\n51NOD\nBaidu Zhidao\nBaidu Wenku\n","date":"2016-08-09T18:14:29+08:00","permalink":"https://boiltask.com/en/knowledge/knapsack-problem/","title":"Knapsack — The Greedy Trap"},{"content":" An adjacency list is a data structure commonly used in graph theory.\nHow to build an adjacency list — template, and when to pick a list over a matrix\nAn adjacency list does roughly what an adjacency matrix does: it stores every edge of a graph. The difference is that a matrix wastes memory — with small data an adjacency matrix is still workable,\nbut once the data grows, a matrix usually runs out of time or memory, and that is when you switch to an adjacency list. To make the two representations easier to compare, let\u0026rsquo;s fix a small data set:\n1 10 3 5 8 9\nWe mark the given points with 1 and leave the rest 0. (1) Adjacency matrix (fine for small, dense graphs)\n/ 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 As you can see, three points force us to allocate a 10x10 two-dimensional array — a large waste of space.\nWalking such a graph with big data can also run out of time. So what about an adjacency list?\n(2) Adjacency list (fine for large, sparse graphs)\nStill the same three points:\nV1————\u0026gt;V10\nV3————\u0026gt;V5\nV8————\u0026gt;V9\nOne chain per vertex is all it takes, which saves a lot of memory. The picture below shows the detail:\nHere is a general template for building an adjacency list:\ncpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 #include\u0026lt;stdio.h\u0026gt; #include\u0026lt;string.h\u0026gt; int n,m; int head[10010];// head of the list; head[i] is the index of the first edge starting at i int headcnt;// total number of edges struct List { int u,v,w;// start vertex, end vertex and weight of the edge int next;// index of the next edge at call time // that is, the index of the previous edge of the current one } edge[10010];// the struct array that stores the edges void add(int u,int v,int w) { edge[headcnt].u=u; edge[headcnt].v=v; edge[headcnt].w=w; // store u, v and w into the edge record edge[headcnt].next=head[u]; // remember the previous edge of this one (the next one at call time) head[u]=headcnt++; // record the index of this edge, which starts at u, // and bump the total index } int main() { while(scanf(\u0026#34;%d %d\u0026#34;,\u0026amp;n,\u0026amp;m)!=EOF) { headcnt=0; memset(head,-1,sizeof(head)); while(m--) { int u,v,w; scanf(\u0026#34;%d %d %d\u0026#34;,\u0026amp;u,\u0026amp;v,\u0026amp;w); add(u,v,w);// read u, v, w and store them in the list } int t; scanf(\u0026#34;%d\u0026#34;,\u0026amp;t); // find the highest-index edge starting at t and walk backwards // until there is no edge before the current one for(int i=head[t]; i!=-1; i=edge[i].next) { printf(\u0026#34;%d %d\\n\u0026#34;,edge[i].v,edge[i].w); } } return 0; } Reference: How to build an adjacency list — template, and when to pick a list over a matrix\n","date":"2016-08-02T16:51:35+08:00","permalink":"https://boiltask.com/en/knowledge/adjacency-list/","title":"Creating and Using Adjacency Lists"},{"content":"Binary search is not so much an algorithm as a way of thinking.\nCore code cpp 1 2 3 4 5 6 7 while(l\u0026lt;=r) { mid=(l+r)/2; if(judge(mid)) { r=mid-1; } else l=mid+1; } Advantages It brings an ordinary search down from O(n) to O(log n).\nRequirements The data you search must be sorted.\nExplanation Binary search shrinks the range in which the answer can lie, again and again, until the optimum is found. In coursework and in contests you will often meet problems that combine binary thinking with some other algorithm.\nUses Finding a value in a sorted array Binary search can answer, for a given array,\nwhether a value exists where that value sits Solving an equation within a tolerance Halve the interval over and over until the solution is precise enough.\nMaximising the minimum Minimising the average Problems of this shape are easy to compare because you can tell whether a candidate is above or below the real answer. So even without knowing what the answer is, you can shrink its range by comparison.\nReference:\nProgramming Contest Challenge Book\nBaidu Baike\n","date":"2016-07-26T17:24:57+08:00","permalink":"https://boiltask.com/en/knowledge/binary-search/","title":"Binary Search — Thinking by Comparing with the Answer"},{"content":"Euclidean algorithm Task Find the greatest common divisor gcd(a, b) of two integers a and b.\nExplanation By Bézout\u0026rsquo;s identity [if a and b are integers, there exist integers x and y such that ax + by = gcd(a, b)], we have gcd(a, b) = gcd(b, a - b) with a ≥ b. Iterating like this until b = 0 yields the gcd of the original pair. Pure subtraction would be too slow, so observe that while a - b is still larger than b the same operation runs again — we can subtract b from a until a is smaller than b. Hence gcd(a, b) = gcd(b, a mod b), which finds the gcd in logarithmic time.\nPrototype int gcd(int a, int b);\nComplexity O(log N), where N is on the same order as a and b.\nInput Two integers a and b.\nOutput The gcd of a and b.\nCode cpp 1 2 3 int gcd(int a,int b){ return b == 0? a : gcd(b, a % b); } Extended Euclidean algorithm Task Find the gcd of A and B, and find X and Y such that AX + BY = GCD(A, B).\nExplanation We need X and Y satisfying AX + BY = GCD(A, B). When B = 0, X = 1 and Y = 0 do the job. When B \u0026gt; 0, building on the Euclidean algorithm, we know: GCD(A, B) = GCD(B, A mod B) First recurse to obtain X\u0026rsquo; and Y\u0026rsquo; satisfying: B X\u0026rsquo; + (A mod B) Y\u0026rsquo; = GCD(B, A mod B) = GCD(A, B) Then expand and work backwards: B X\u0026rsquo; + (A - A/BB) Y\u0026rsquo; = GCD(A, B) A Y\u0026rsquo; + B X\u0026rsquo; - (A/B)B Y\u0026rsquo; = GCD(A, B) Here the division is integer division. Collecting the terms that contain B: A Y\u0026rsquo; + B (X\u0026rsquo; - A/BY\u0026rsquo;) = GCD(A, B) Therefore X = Y\u0026rsquo;, Y = X\u0026rsquo; - A/BY'\nPrototype int extend_gcd(int a, int b, int \u0026amp;x, int \u0026amp;y);\nComplexity O(log N), where N is on the same order as a and b.\nInput Two integers a and b, plus the references \u0026amp;x and \u0026amp;y for one solution of ax + by = GCD(a, b).\nOutput The gcd of a and b; after the call, x and y satisfy ax + by = GCD(a, b).\nCode 1 2 3 4 5 6 7 8 9 10 11 int extend_gcd(int a,int b,int \u0026amp;x,int \u0026amp;y) { if(b==0) { x=1; y=0; return a; } else { int r=extend_gcd(b,a%b,y,x); y-=x*(a/b); return r; } } References ACM International Collegiate Programming Contest: Algorithms and Implementations Baidu Baike\n","date":"2016-07-21T15:08:12+08:00","permalink":"https://boiltask.com/en/knowledge/extended-gcd/","title":"Euclid — A Discussion Sparked by GCD"},{"content":"Example problems:\nThere are N computers and K tasks, and each computer can handle a different set of task types — how many tasks can be handled at most?\nOn a roller coaster every girl is willing to sit next to only a few particular boys — how many pairs can be arranged at most?\nHungarian algorithm\nReferences:\nProgramming Contest Challenge Book\nCompetitive Programming (the classic introduction to contest algorithms)\nHungarian algorithm — Baidu Baike\nA playful take on the Hungarian algorithm\n","date":"2016-04-01T07:07:18+08:00","permalink":"https://boiltask.com/en/knowledge/bipartite-graph/","title":"Bipartite Graph — Matching Items from One Set into Another"},{"content":"Problem statement 兰州烧饼 Time limit: 1000 msMemory limit: 64 MB Description A pancake has two sides. You have one large griddle that can hold k Lanzhou pancakes at a time, and one minute cooks one side. Given n pancakes, what is the minimum number of minutes needed to cook all of them?\nInput n and k, separated by a space, where 1 \u0026lt;= k, n \u0026lt;= 100000.\nOutput The minimum number of minutes needed to cook every pancake.\nSample Input 1 3 2 Sample Output 1 3 Hint For the sample: pancakes a, b and c — first a and b, then a and c, finally b and c. Done in 3 minutes.\nAnalysis Let\u0026rsquo;s make this brain teaser the 200th node~ I did one on ZZULI before where the pan held exactly 2 this one has k as a variable\nStill, the same idea applies: look for the pattern\n\u0026mdash;\u0026ndash;k=1\u0026mdash;\u0026ndash;\nwhatever you do, it takes n*2\n\u0026mdash;\u0026ndash;k=2\u0026mdash;\u0026ndash;\n2 when n==1, otherwise n\n2 when n\u0026lt;3\n3 when n=4/5\n4 when n=6\n……\n\u0026mdash;\u0026ndash;……\u0026mdash;\u0026ndash;\nThen you notice the answer depends on\nn*2/k\nthat is, the smallest value not below n*2/k\nAnd when n\u0026lt;k\nit always takes 2 minutes\nSo the code is\ncpp 1 2 3 4 5 6 7 8 9 10 11 12 #include\u0026lt;stdio.h\u0026gt; #include\u0026lt;math.h\u0026gt; int main() { int n,k; while(scanf(\u0026#34;%d %d\u0026#34;,\u0026amp;n,\u0026amp;k)!=EOF) { if(n\u0026lt;=k) printf(\u0026#34;2\\n\u0026#34;); else printf(\u0026#34;%.lf\\n\u0026#34;,ceil(n*2.0/k)); } return 0; } Problem link: [NYOJ][799] Lanzhou Pancake\n","date":"2016-02-21T04:31:06+08:00","permalink":"https://boiltask.com/en/oj/nyoj-v1-799/","title":"[NYOJ] [v1-799] Lanzhou Pancake"},{"content":"Single-source shortest path Finding the shortest path from one vertex to every other vertex.\nShortest path with BFS Competitive Programming\nChapter 6, the graph part — zzyafyj\u0026rsquo;s column\nDijkstra Algorithms on the toilet, part 7: Dijkstra\u0026rsquo;s shortest path\nWe find dis[3] = 12, while dis[2] + e[2][3] = 1 + 9 = 10. Since dis[3] \u0026gt; dis[2] + e[2][3], dis[3] must be updated to 10. This process has a name: \u0026ldquo;relaxation\u0026rdquo;. The distance from vertex 1 to vertex 3 — dis[3] — is successfully relaxed through the edge 2-\u0026gt;3. That is the main idea of Dijkstra: relax the distances from vertex 1 to all the other vertices through edges.\nEach time, take the vertex closest to the source (vertex 1 in the example), expand from it as the new centre, and you eventually get the shortest paths from the source to all remaining vertices.\nAll-pairs shortest paths Finding the shortest path between every pair of vertices.\nFloyd–Warshall Algorithms on the toilet: Floyd\u0026rsquo;s shortest path in five lines\nAt first only vertex 1 may be used as an intermediate point, then only vertices 1 and 2, … and finally all vertices 1..n. Put in one sentence: the shortest path from vertex i to vertex j using only the first k vertices as intermediates.\nReference:\nProgramming Contest Challenge Book\nAlgorithms on the toilet: Floyd\u0026rsquo;s shortest path in five lines\nAlgorithms on the toilet, part 7: Dijkstra\u0026rsquo;s shortest path\n","date":"2016-02-17T14:49:25+08:00","permalink":"https://boiltask.com/en/knowledge/shortest-path/","title":"Shortest Path — Minimum Total Weight Between Two Vertices"},{"content":"I learned the difference between\nwhile and do-while long ago,\nbut do-while is rarely used —\nI can honestly say I never used it in a problem.\nSo when people say\nthe body of a do-while loop runs at least once\nI never really felt it.\nWhat triggered this reflection was\n【NYOJ】[56] Factorial factorisation (1)\nand its for-loop condition\nfor(int k=i; !(k%m); cnt++) The meaning of !(k%m) puzzled me a little.\nBut with while and do-while in mind it falls out easily:\nfor(init; condition; update)\nexecutes in this order:\nflowchart TD st[init] --\u0026gt; cond{condition} cond -- yes --\u0026gt; op1[loop body] cond -- no --\u0026gt; e[end] op1 --\u0026gt; op2[update] op2 --\u0026gt; cond Not a bad flowchart, eh~ hahaha\nVerification:\nThe init statement runs before the first test:\ncpp 1 2 3 4 5 6 7 #include\u0026lt;stdio.h\u0026gt; int main() { int n=1; for(int i=n=0; i\u0026lt;0; n++,i++); printf(\u0026#34;n is %d\\n\u0026#34;,n); return 0; } The condition is tested before the body runs for the first time:\ncpp 1 2 3 4 5 6 7 8 9 10 #include\u0026lt;stdio.h\u0026gt; int main() { int n=0; for(int i=0; i\u0026lt;0; i++) n++; //\tfor(int i=0; i\u0026lt;1; i++) //\tn++; printf(\u0026#34;ran %d times\\n\u0026#34;,n); return 0; } And the do-while form:\ncpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include\u0026lt;stdio.h\u0026gt; int main() { int n=0; int i=0; do { n++; i++; } while(i\u0026lt;0); //\tdo { //\tn++; //\ti++; //\t} while(i\u0026lt;1); printf(\u0026#34;n is %d\\n\u0026#34;,n); return 0; } Both print n is 1.\nWhich verifies\nthe difference between for and do-while\n","date":"2016-01-25T12:12:22+08:00","permalink":"https://boiltask.com/en/knowledge/cpp/for-do-while/","title":"for, (do-)while — How the Loop Body Executes"}]