結果

問題 No.416 旅行会社
ユーザー fmhrfmhr
提出日時 2016-08-27 00:13:51
言語 Go
(1.22.1)
結果
TLE  
実行時間 -
コード長 2,073 bytes
コンパイル時間 12,629 ms
コンパイル使用メモリ 220,504 KB
実行使用メモリ 23,292 KB
最終ジャッジ日時 2024-04-26 04:17:49
合計ジャッジ時間 23,578 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 TLE -
testcase_01 -- -
testcase_02 -- -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

package main

import (
	"bufio"
	"os"
	"strconv"
	"fmt"
)

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*100000+crash[i].b] = true
	}

	uf := makeUnionFind(n + 1)
	// 壊れない橋を追加する
	for i := 0; i < m; i++ {
		if crashed[bridge[i].a*100000+bridge[i].b] {
			continue
		}
		//fmt.Println("追加1: ", bridge[i].a, bridge[i].b)
		uf.Unit(bridge[i].a, bridge[i].b)
	}
	ans := make([]int, n+1)
	for i:=2; i<n; i++ {
		if uf.isConnect(1, i) {
			ans[i] = -2
		}
	}
	// 壊れる橋を逆順に追加しながら、つながっているかチェックする
	for i := q - 1; i >= 0; i-- {
		//fmt.Println("追加逆順1:",i,crash[i].a, crash[i].b)
		uf.Unit(crash[i].a, crash[i].b)
		for j := 2; j <= n; j++ {
			if uf.isConnect(1, j) && ans[j]==0 {
				ans[j] = i
			}
		}
		//fmt.Println("毎回解答:", i, ans)
	}
	for i := 2; i < n+1; i++ {
		fmt.Println(ans[i]+1)
	}
}

type nodes struct {
	a, b int
}

type UnionFind struct {
	par    []int // 親
	weight []int // 重み
}

func makeUnionFind(count int) *UnionFind {
	par := make([]int, count)
	weight := make([]int, count)
	for i := 0; i < count; i++ {
		par[i] = i
		weight[i] = 1
	}
	return &UnionFind{par: par, weight: weight}
}

func (uf *UnionFind) Find(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) Unit(a, b int) {
	a = uf.Find(a)
	b = uf.Find(b)
	if a == b {
		return
	}
	if uf.weight[a] > uf.weight[b] {
		a, b = b, a
	}
	uf.par[a] = b
	uf.weight[b] += uf.weight[a]
}

func (uf *UnionFind) isConnect(a, b int) bool {
	return uf.Find(a) == uf.Find(b)
}

var sc = bufio.NewScanner(os.Stdin)

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	i, _ := strconv.Atoi(nextLine())
	return i
}
0