結果

問題 No.1745 Selfish Spies 2 (à la Princess' Perfectionism)
ユーザー koba-e964koba-e964
提出日時 2021-11-14 23:34:39
言語 Rust
(1.77.0 + proconio)
結果
AC  
実行時間 922 ms / 5,000 ms
コード長 10,191 bytes
コンパイル時間 19,609 ms
コンパイル使用メモリ 379,284 KB
実行使用メモリ 100,824 KB
最終ジャッジ日時 2024-05-07 15:44:50
合計ジャッジ時間 24,809 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 1 ms
5,248 KB
testcase_02 AC 1 ms
5,376 KB
testcase_03 AC 1 ms
5,376 KB
testcase_04 AC 1 ms
5,376 KB
testcase_05 AC 1 ms
5,376 KB
testcase_06 AC 1 ms
5,376 KB
testcase_07 AC 1 ms
5,376 KB
testcase_08 AC 1 ms
5,376 KB
testcase_09 AC 1 ms
5,376 KB
testcase_10 AC 1 ms
5,376 KB
testcase_11 AC 1 ms
5,376 KB
testcase_12 AC 1 ms
5,376 KB
testcase_13 AC 1 ms
5,376 KB
testcase_14 AC 2 ms
5,376 KB
testcase_15 AC 2 ms
5,376 KB
testcase_16 AC 2 ms
5,376 KB
testcase_17 AC 3 ms
5,376 KB
testcase_18 AC 4 ms
5,376 KB
testcase_19 AC 1 ms
5,376 KB
testcase_20 AC 1 ms
5,376 KB
testcase_21 AC 1 ms
5,376 KB
testcase_22 AC 1 ms
5,376 KB
testcase_23 AC 2 ms
5,376 KB
testcase_24 AC 10 ms
5,376 KB
testcase_25 AC 3 ms
5,376 KB
testcase_26 AC 3 ms
5,376 KB
testcase_27 AC 6 ms
5,376 KB
testcase_28 AC 47 ms
16,384 KB
testcase_29 AC 5 ms
5,376 KB
testcase_30 AC 5 ms
5,376 KB
testcase_31 AC 5 ms
5,376 KB
testcase_32 AC 4 ms
5,376 KB
testcase_33 AC 44 ms
16,512 KB
testcase_34 AC 40 ms
16,384 KB
testcase_35 AC 48 ms
15,872 KB
testcase_36 AC 52 ms
16,000 KB
testcase_37 AC 50 ms
15,744 KB
testcase_38 AC 42 ms
15,872 KB
testcase_39 AC 32 ms
8,300 KB
testcase_40 AC 40 ms
12,480 KB
testcase_41 AC 39 ms
12,492 KB
testcase_42 AC 92 ms
22,868 KB
testcase_43 AC 130 ms
30,912 KB
testcase_44 AC 195 ms
39,904 KB
testcase_45 AC 630 ms
65,340 KB
testcase_46 AC 694 ms
65,336 KB
testcase_47 AC 920 ms
98,008 KB
testcase_48 AC 922 ms
97,972 KB
testcase_49 AC 234 ms
30,720 KB
testcase_50 AC 214 ms
30,956 KB
testcase_51 AC 72 ms
12,160 KB
testcase_52 AC 59 ms
19,028 KB
testcase_53 AC 77 ms
18,772 KB
testcase_54 AC 203 ms
40,484 KB
testcase_55 AC 190 ms
40,768 KB
testcase_56 AC 498 ms
42,000 KB
testcase_57 AC 764 ms
100,824 KB
testcase_58 AC 831 ms
100,812 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes.by_ref().map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr,) => {};
    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => { ($(read_value!($next, $t)),*) };
    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };
    ($next:expr, usize1) => (read_value!($next, usize) - 1);
    ($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error"));
}

/**
 * Dinic's algorithm for maximum flow problem.
 * Verified by: yukicoder No.177 (http://yukicoder.me/submissions/148371)
 * Min-cut (the second element of max_flow's returned values) is not verified.
 */

#[derive(Clone)]
struct Edge<T> {
    to: usize,
    cap: T,
    rev: usize, // rev is the position of the reverse edge in graph[to]
}

struct Dinic<T> {
    graph: Vec<Vec<Edge<T>>>,
    iter: Vec<usize>,
    zero: T,
}

impl<T> Dinic<T>
    where T: Clone,
          T: Copy,
          T: Ord,
          T: std::ops::AddAssign,
          T: std::ops::SubAssign,
{
    fn bfs(&self, s: usize, level: &mut [Option<usize>]) {
        let n = level.len();
        for i in 0 .. n {
            level[i] = None;
        }
        let mut que = std::collections::VecDeque::new();
        level[s] = Some(0);
        que.push_back(s);
        while let Some(v) = que.pop_front() {
            for e in self.graph[v].iter() {
	        if e.cap > self.zero && level[e.to] == None {
	            level[e.to] = Some(level[v].unwrap() + 1);
	            que.push_back(e.to);
                }
            }
	}
    }
    /* search augment path by dfs.
     * if f == None, f is treated as infinity.
     */
    fn dfs(&mut self, v: usize, t: usize, f: Option<T>, level: &mut [Option<usize>]) -> T {
        if v == t {
            return f.unwrap();
        }
        while self.iter[v] < self.graph[v].len() {
            let i = self.iter[v];
            let e = self.graph[v][i].clone();
            if e.cap > self.zero && level[v] < level[e.to] {
                let newf = std::cmp::min(f.unwrap_or(e.cap), e.cap);
                let d = self.dfs(e.to, t, Some(newf), level);
                if d > self.zero {
                    self.graph[v][i].cap -= d;
                    self.graph[e.to][e.rev].cap += d;
                    return d;
                }
            }
            self.iter[v] += 1;
        }
        self.zero
    }
    pub fn new(n: usize, zero: T) -> Self {
        Dinic {
            graph: vec![Vec::new(); n],
            iter: vec![0; n],
            zero: zero,
        }
    }
    pub fn add_edge(&mut self, from: usize, to: usize, cap: T) {
        let added_from = Edge { to: to, cap: cap,
                            rev: self.graph[to].len() };
        let added_to = Edge { to: from, cap: self.zero,
                            rev: self.graph[from].len() };
        self.graph[from].push(added_from);
        self.graph[to].push(added_to);
    }
    pub fn max_flow(&mut self, s: usize, t: usize) -> (T, Vec<usize>) {
        let mut flow = self.zero;
        let n = self.graph.len();
        let mut level = vec![None; n];
        loop {
            self.bfs(s, &mut level);
            if level[t] == None {
                let ret = (0 .. n).filter(|&i| level[i] == None)
                    .collect();
                return (flow, ret);
            }
            self.iter.clear();
            self.iter.resize(n, 0);
            loop {
                let f = self.dfs(s, t, None, &mut level);
                if f <= self.zero { break; }
                flow += f;
            }
        }
    }
}

// Strong connected components.
// Verified by: yukicoder No.470 (http://yukicoder.me/submissions/145785)
//              ABC214-H (https://atcoder.jp/contests/abc214/submissions/25082618)
struct SCC {
    n: usize,
    ncc: usize,
    g: Vec<Vec<usize>>, // graph in adjacent list
    rg: Vec<Vec<usize>>, // reverse graph
    cmp: Vec<usize>, // topological order
}

impl SCC {
    fn new(n: usize) -> Self {
        SCC {
            n: n,
            ncc: n + 1,
            g: vec![Vec::new(); n],
            rg: vec![Vec::new(); n],
            cmp: vec![0; n],
        }
    }
    fn add_edge(&mut self, from: usize, to: usize) {
        self.g[from].push(to);
        self.rg[to].push(from);
    }
    fn dfs(&self, v: usize, used: &mut [bool], vs: &mut Vec<usize>) {
        used[v] = true;
        for &w in self.g[v].iter() {
            if !used[w] {
               self.dfs(w, used, vs);
            }
        }
        vs.push(v);
    }
    fn rdfs(&self, v: usize, k: usize,
            used: &mut [bool], cmp: &mut [usize]) {
        used[v] = true;
        cmp[v] = k;
        for &w in self.rg[v].iter() {
            if !used[w] {
                self.rdfs(w, k, used, cmp);
            }
        }
    }
    fn scc(&mut self) -> usize {
        let n = self.n;
        let mut used = vec![false; n];
        let mut vs = Vec::new();
        let mut cmp = vec![0; n];
        for v in 0 .. n {
            if !used[v] { self.dfs(v, &mut used, &mut vs); }
        }
        for u in used.iter_mut() {
            *u = false;
        }
        let mut k = 0;
        for &t in vs.iter().rev() {
            if !used[t] { self.rdfs(t, k, &mut used, &mut cmp); k += 1; }
        }
        self.ncc = k;
        self.cmp = cmp;
        k
    }
    #[allow(dead_code)]
    fn top_order(&self) -> Vec<usize> {
        assert!(self.ncc <= self.n);
        self.cmp.clone()
    }
    /*
     * Returns a dag whose vertices are scc's, and whose edges are those of the original graph.
     */
    #[allow(dead_code)]
    fn dag(&self) -> Vec<Vec<usize>> {
        assert!(self.ncc <= self.n);
        let ncc = self.ncc;
        let mut ret = vec![vec![]; ncc];
        let n = self.n;
        for i in 0 .. n {
            for &to in self.g[i].iter() {
                if self.cmp[i] != self.cmp[to] {
                    assert!(self.cmp[i] < self.cmp[to]);
                    ret[self.cmp[i]].push(self.cmp[to]);
                }
            }
        }
        ret.into_iter().map(|mut v| {
            v.sort_unstable(); v.dedup();
            v
        }).collect()
    }
    #[allow(dead_code)]
    fn rdag(&self) -> Vec<Vec<usize>> {
        assert!(self.ncc <= self.n);
        let ncc = self.ncc;
        let mut ret = vec![vec![]; ncc];
        let n = self.n;
        for i in 0 .. n {
            for &to in self.g[i].iter() {
                if self.cmp[i] != self.cmp[to] {
                    assert!(self.cmp[i] < self.cmp[to]);
                    ret[self.cmp[to]].push(self.cmp[i]);
                }
            }
        }
        ret.into_iter().map(|mut v| {
            v.sort_unstable(); v.dedup();
            v
        }).collect()
    }
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}

fn reach(init: &[usize], g: &[Vec<usize>], mid: usize) -> (Vec<usize>, Vec<usize>) {
    let n = g.len();
    let mut que = init.iter().cloned().collect::<VecDeque<_>>();
    let mut vis = vec![false; n];
    while let Some(v) = que.pop_front() {
        if vis[v] { continue; }
        vis[v] = true;
        for &w in &g[v] {
            if !vis[w] { que.push_back(w); }
        }
    }
    let fst = (0..mid).filter(|&i| vis[i]).collect();
    let snd = (mid..n).filter(|&i| vis[i]).collect();
    (fst, snd)
}

// Tags: dulmage–mendelsohn-decomposition, dm-decomposition, matchings
// Ref: http://www.misojiro.t.u-tokyo.ac.jp/~murota/lect-ouyousurigaku/dm050410.pdf
fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {($($format:tt)*) => (let _ = write!(out,$($format)*););}
    input! {
        n: usize, m: usize, l: usize,
        ab: [(usize1, usize1); l],
    }
    let mut din = Dinic::new(2 + n + m, 0);
    for i in 0..n {
        din.add_edge(0, 2 + i, 1);
    }
    for i in 0..m {
        din.add_edge(2 + n + i, 1, 1);
    }
    for &(a, b) in &ab {
        din.add_edge(2 + a, 2 + n + b, 1);
    }
    let _ = din.max_flow(0, 1);
    let mut g = vec![vec![]; n + m];
    let mut revg = vec![vec![]; n + m];
    let mut scc = SCC::new(n + m);
    for &(a, b) in &ab {
        scc.add_edge(a, n + b);
        g[a].push(n + b);
        revg[n + b].push(a);
    }
    let mut unmatched = vec![true; n + m];
    let mut mm = vec![];
    for i in 0..m {
        for e in &din.graph[2 + n + i] {
            if e.to >= 2 && e.cap == 1 {
                scc.add_edge(n + i, e.to - 2);
                mm.push((e.to - 2, i));
                unmatched[e.to - 2] = false;
                unmatched[n + i] = false;
                g[n + i].push(e.to - 2);
                revg[e.to - 2].push(n + i);
            }
        }
    }
    let ncc = scc.scc();
    let mut top_ord = scc.top_order();
    let left: Vec<_> = (0..n).filter(|&i| unmatched[i]).collect();
    let (v0a, v0b) = reach(&left, &g, n);
    let right: Vec<_> = (n..n + m).filter(|&i| unmatched[i]).collect();
    let (vinfa, vinfb) = reach(&right, &revg, n);
    for &v in v0a.iter().chain(&v0b) {
        top_ord[v] = ncc;
    }
    for &v in vinfa.iter().chain(&vinfb) {
        top_ord[v] = ncc + 1;
    }
    for i in 0..l {
        let (a, b) = ab[i];
        puts!("{}\n", if top_ord[a] == top_ord[n + b] { "Yes" } else { "No" });
    }
}
0