結果
| 問題 |
No.416 旅行会社
|
| コンテスト | |
| ユーザー |
fmhr
|
| 提出日時 | 2016-08-27 06:55:45 |
| 言語 | Go (1.23.4) |
| 結果 |
AC
|
| 実行時間 | 268 ms / 4,000 ms |
| コード長 | 2,501 bytes |
| コンパイル時間 | 12,246 ms |
| コンパイル使用メモリ | 222,004 KB |
| 実行使用メモリ | 25,984 KB |
| 最終ジャッジ日時 | 2024-12-14 20:00:35 |
| 合計ジャッジ時間 | 16,617 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 21 |
ソースコード
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
sc.Split(bufio.ScanWords)
n := nextInt()
m := nextInt()
q := nextInt()
bridge := make([]nodes, m)
for i := 0; i < m; i++ {
bridge[i].a = nextInt()
bridge[i].b = nextInt()
}
crashed := make(map[int]bool)
crash := make([]nodes, q)
for i := 0; i < q; i++ {
crash[i].a = nextInt()
crash[i].b = nextInt()
crashed[crash[i].a*1000000+crash[i].b] = true
}
uf := makeUnionFind(n + 1)
// 壊れない橋を追加する
for i := 0; i < m; i++ {
if !crashed[bridge[i].a*1000000+bridge[i].b] {
//fmt.Println("追加1: ", bridge[i].a, bridge[i].b)
uf.Set(bridge[i].a, bridge[i].b)
}
}
ans := make([]int, n+1)
// 1とつながっている島
for _, i := range uf.link[uf.Root(1)] {
ans[i] = -1
}
//fmt.Println("-1ケース, ", ans)
// 壊れる橋を逆順に追加しながら、つながっているかチェックする
for i := q - 1; i >= 0; i-- {
//fmt.Println("追加逆順1:",i,crash[i].a, crash[i].b)
x := crash[i].a
y := crash[i].b
if uf.Same(x, y) {
continue
}
if uf.Same(1, uf.Root(y)) {
x, y = y, x
}
if uf.Same(1, x) {
for _, h := range uf.link[uf.Root(y)] {
if ans[h] == 0 {
ans[h] = i + 1
}
}
}
uf.Set(x, y)
//fmt.Println("毎回解答:", i, ans)
}
for i := 2; i <= n; i++ {
fmt.Println(ans[i])
}
}
type nodes struct {
a, b int
}
type UnionFind struct {
par []int // 親
size []int // 重み
link [][]int // グループ
}
func makeUnionFind(count int) *UnionFind {
par := make([]int, count)
size := make([]int, count)
link := makeDoubleSliceInt(count, 1)
for i := 0; i < count; i++ {
par[i] = i
size[i] = 1
link[i][0] = i
}
return &UnionFind{par: par, size: size, link: link}
}
func (uf *UnionFind) Root(a int) int {
for uf.par[a] != a {
uf.par[a] = uf.par[uf.par[a]]
a = uf.par[a]
}
return a
}
func (uf *UnionFind) Set(a, b int) {
a = uf.Root(a)
b = uf.Root(b)
if a != b {
if uf.size[a] > uf.size[b] {
a, b = b, a
}
uf.par[a] = b
uf.size[b] += uf.size[a]
uf.link[b] = append(uf.link[b], uf.link[a]...)
}
}
func (uf *UnionFind) Same(a, b int) bool {
return uf.Root(a) == uf.Root(b)
}
func makeDoubleSliceInt(y, x int) (r [][]int) {
r = make([][]int, y)
for i := range r {
r[i] = make([]int, x)
}
return
}
var sc = bufio.NewScanner(os.Stdin)
func nextLine() string {
sc.Scan()
return sc.Text()
}
func nextInt() int {
i, _ := strconv.Atoi(nextLine())
return i
}
fmhr