for i := 1; i <= n; i++ { s := strconv.Itoa(i * i) n := len(s) var dfs func(int, int)bool dfs = func(p int, sum int)bool { if p == n { // 切割到最后一位,判断是否符合要求 return sum == i } x := 0 for j := p; j < n; j++ { x = x*10 + int(s[j]-'0') if dfs(j+1, sum+x) { returntrue } } returnfalse } if dfs(0, 0) { sum += i * i } } return sum }
funcmodifiedGraphEdges(n int, edges [][]int, source int, destination int, target int) [][]int { type edge struct { to, eid int// eid方便后续修改edges } graph := make([][]edge, n) for i, e := range edges { form, to := e[0], e[1] graph[form] = append(graph[form], edge{to, i}) graph[to] = append(graph[to], edge{form, i}) }
var delta int dis := make([][2]int, n) for i := range dis { dis[i] = [2]int{math.MaxInt, math.MaxInt} } dis[source] = [2]int{} dijkstra := func(k int) { vis := make([]bool, n) for { // 找到最短路,并且没有vis的点,(第一轮循环找的是起点 source) x := -1 for y, b := range vis { if !b && (x < 0 || dis[y][k] < dis[x][k]) { x = y } }
if x == destination { // 起点source到终点 destination的最短距离已确认 return } vis[x] = true for _, e := range graph[x] { y, wt := e.to, edges[e.eid][2] if wt == -1 { wt = 1// -1改为1 } if k == 1 && edges[e.eid][2] == -1 { // 第二次 Dijkstra,改成 w w := delta + dis[y][0] - dis[x][1] if w > wt { wt = w edges[e.eid][2] = w } } // 更新最短路 dis[y][k] = min(dis[y][k], dis[x][k]+wt) } } }