题目:
解题思路:
解题代码:
package main import ( "fmt" ) var n int var res []int func main() { var ( m int p int ) fmt.Scan(&n) fmt.Scan(&m) fmt.Scan(&p) // 画圈 res = make([]int,n+1) // 初始化关系 for i := 1; i < n + 1; i++ { res[i] = i } for i := 0; i < m; i++ { a := 0 b := 0 fmt.Scan(&a) fmt.Scan(&b) join(a,b) } //for i := 1; i < n+1; i++ { // fmt.Print(res[i]," ") // //} // 检查 var ps = make([][]int,p) for i := 0; i < p; i++ { a := 0 b := 0 fmt.Scan(&a) fmt.Scan(&b) ps[i] = append(ps[i],a,b) } // 如果能在a的关系中找到b就说明a和b有关系 for i := 0; i < p; i++ { if judge(ps[i][0],ps[i][1],ps[i][0]) { fmt.Println("YES") } else { fmt.Println("NO") } } } func join(a,b int) { if judge(a,b,a) { return } // 找出a的下个元素 v := res[a] // 找出靠b最近的最后一个元素 k := find(b,b) //fmt.Print(k,"= k",v,"= v") res[a] = b res[k] = v } func find(i,j int) int { // fmt.Print(res[i],"") if res[i] == j { return i } return find(res[i],j) } func judge(a,b,c int) bool { //fmt.Print(res[a]," ") if res[a] == b { return true } if res[a] == c { return false } return judge(res[a],b,c) }