結果
| 問題 | No.1565 Union |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2021-12-19 10:25:36 |
| 言語 | Go (1.23.4) |
| 結果 |
AC
|
| 実行時間 | 464 ms / 2,000 ms |
| コード長 | 2,202 bytes |
| コンパイル時間 | 13,732 ms |
| コンパイル使用メモリ | 230,460 KB |
| 実行使用メモリ | 24,832 KB |
| 最終ジャッジ日時 | 2024-12-20 19:34:10 |
| 合計ジャッジ時間 | 21,807 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 27 |
ソースコード
package main
import (
"fmt"
"bufio"
"os"
"math"
)
type Cell struct {
item int
next *Cell
}
func newCell(item int, cp *Cell) *Cell {
newcp := new(Cell)
newcp.item, newcp.next = item, cp
return newcp
}
type Queue struct {
size int
front, rear *Cell
}
func newQueue() *Queue {
newqp := new(Queue)
newqp.size, newqp.front, newqp.rear = 0, nil, nil
return newqp
}
func (q *Queue) enqueue(item int) {
cp := newCell(item, nil)
if q.size == 0 {
q.front = cp
q.rear = cp
} else {
q.rear.next = cp
q.rear = cp
}
q.size++
}
func (q *Queue) dequeue() (int, bool) {
if q.size == 0 {
return 0, false
} else {
item := q.front.item
q.front = q.front.next
q.size--
if q.size == 0 {
q.rear = nil
}
return item, true
}
}
func (q *Queue) isEmpty() bool {
return q.size == 0
}
type CellMgr struct {
top, cp, last *Cell
}
func newCellMgr() *CellMgr {
cmp := new(CellMgr)
cmp.top = nil
cmp.cp = nil
cmp.last = nil
return cmp
}
func (this *CellMgr) iterator() *CellMgr{
this.cp = this.top
return this
}
func (this *CellMgr) append(item int) {
ncp := newCell(item, nil)
if this.top == nil {
this.top = ncp
this.last = ncp
} else {
this.last.next = ncp
this.last = ncp
}
}
func (this *CellMgr) isNext() bool {
return this.cp != nil
}
func (this *CellMgr) next() (int, bool) {
cp := this.cp
if cp != nil {
this.cp = cp.next
return cp.item, true
} else {
return 0, false
}
}
func main() {
r := bufio.NewReader(os.Stdin)
w := bufio.NewWriter(os.Stdout)
defer w.Flush()
var N, M int
fmt.Fscan(r, &N, &M)
road := make([]*CellMgr, N)
d := make([]int, N)
for i := 0; i < N; i++ {
road[i] = newCellMgr()
d[i] = math.MaxInt64
}
for i := 0; i < M; i++ {
var a, b int
fmt.Fscan(r, &a, &b)
road[a-1].append(b-1)
road[b-1].append(a-1)
}
d[0] = 0
q := newQueue()
q.enqueue(0)
var fin bool = false
for !fin && !q.isEmpty() {
v, _ := q.dequeue()
rp := road[v].iterator()
for rp.isNext() {
nv , _ := rp.next()
if d[nv] > d[v] + 1 {
d[nv] = d[v] + 1
q.enqueue(nv)
if nv == N-1 {
fin = true
break
}
}
}
}
if fin {
fmt.Fprintln(w, d[N-1])
} else {
fmt.Fprintln(w, -1)
}
}