Problem solution · Go

Codeforces 1542E1 — Abnormal Permutation Pairs (easy version)

Codeforces 1542E1 — Abnormal Permutation Pairs (easy version): a Go solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Direct simulation
Source
EndlessCheng Codeforces Go
Length
48 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Codeforces 1542E1 — Abnormal Permutation Pairs (easy version), the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 48 lines of Go from the credited upstream file 1542E1.go.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from EndlessCheng Codeforces Go by Σndless (EndlessCheng) and is used under the MIT licence.

Full codeCodeforces 1542E1 — Abnormal Permutation Pairs (easy version) · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io") // https://github.com/EndlessChengfunc cf1542E1(in io.Reader, out io.Writer) {	var n, mod, ans int	Fscan(in, &n, &mod) 	maxK := n * (n - 1) / 2	f := make([][]int, n+1)	for i := range f {		f[i] = make([]int, maxK+1)	}	f[0][0] = 1	sum := make([]int, maxK+2)	for i := 1; i <= n; i++ {		mx := i*(i-1)/2 + 1		for j, v := range f[i-1][:mx] {			sum[j+1] = sum[j] + v		}		for j := range mx {			f[i][j] = (sum[j+1] - sum[max(j-i+1, 0)]) % mod		}	} 	perm := 1	for i := n; i > 3; i-- { // 剩余 i 个数:此处枚举 P 和 Q 选什么		row := f[i-1]		res := 0		for delta := 1; delta < i; delta++ { // delta = Q 新增逆序对 - P 新增逆序对,有 i-delta 个方案			s := 0			for j := delta + 1; j <= maxK; j++ { // 枚举 row 中的 P 的逆序对 j,累加 Q 的逆序对 s				s = (s + row[j-delta-1]) % mod				res = (res + row[j]*s%mod*(i-delta)) % mod			}		}		ans = (ans + perm*res) % mod		perm = perm * i % mod	}	Fprint(out, ans)} //func main() { cf1542E1(os.Stdin, os.Stdout) } 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗