Problem solution · Go

Codeforces 520C — DNA Alignment

Codeforces 520C — DNA Alignment: 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
47 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 520C — DNA Alignment, 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

  • 47 lines of Go from the credited upstream file 520C.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 520C — DNA Alignment · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io"	"sort") func Sol520C(reader io.Reader, writer io.Writer) {	in := bufio.NewReader(reader)	out := bufio.NewWriter(writer)	defer out.Flush() 	var n int	var s string	Fscan(in, &n, &s) 	// 找规律,观察发现对于 AAG 这样只有一种字母最多的情况,t 只有一种情况(AAA);	// 对于 AAGGT 这样有 m 种字母一样最多的情况,由于滚动循环的特性,每个匹配位置上出现 A 和出现 G 的情况是一样多的(都为两次),	// 所以 t 的每个字符上是 A 还是 G 对计算结果没有影响,这样答案是 pow(m,n)。	cnts := make([]int, 26)	for _, c := range s {		cnts[c-'A']++	}	sort.Ints(cnts)	m := int64(0)	for _, c := range cnts {		if c == cnts[25] {			m++		}	}	const mod = int64(1e9 + 7)	ans := int64(1)	for ; n > 0; n >>= 1 {		if n&1 == 1 {			ans = ans * m % mod		}		m = m * m % mod	}	Fprintln(out, ans)} //func main() {//	Sol520C(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 ↗