結果
問題 |
No.3201 Corporate Synergy
|
ユーザー |
|
提出日時 | 2025-07-11 22:39:45 |
言語 | Rust (1.83.0 + proconio) |
結果 |
AC
|
実行時間 | 1 ms / 2,000 ms |
コード長 | 14,228 bytes |
コンパイル時間 | 10,235 ms |
コンパイル使用メモリ | 400,016 KB |
実行使用メモリ | 7,716 KB |
最終ジャッジ日時 | 2025-09-01 23:37:06 |
合計ジャッジ時間 | 11,738 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 20 |
コンパイルメッセージ
warning: methods `reserve`, `size`, `empty`, and `front` are never used --> src/main.rs:71:19 | 70 | impl<T> SimpleQueue<T> { | ---------------------- methods in this implementation 71 | pub(crate) fn reserve(&mut self, n: usize) { | ^^^^^^^ ... 77 | pub(crate) fn size(&self) -> usize { | ^^^^ ... 81 | pub(crate) fn empty(&self) -> bool { | ^^^^^ ... 90 | pub(crate) fn front(&self) -> Option<&T> { | ^^^^^ | = note: `#[warn(dead_code)]` on by default warning: field `flow_limit` is never read --> src/main.rs:374:5 | 370 | struct FlowCalculator<'a, Cap> { | -------------- field in this struct ... 374 | flow_limit: Cap, | ^^^^^^^^^^
ソースコード
pub trait SortD{ fn sort_d(&mut self); } impl<T: Ord> SortD for Vec<T>{ fn sort_d(&mut self) { self.sort_by(|u, v| v.cmp(&u)); } } pub trait Mx{fn max(&self, rhs: Self)->Self;} impl Mx for f64{ fn max(&self, rhs: Self)->Self{if *self < rhs{ rhs } else { *self } }} pub trait Mi{ fn min(&self, rhs: Self)->Self; } impl Mi for f64{ fn min(&self, rhs: Self)->Self{ if *self < rhs{ rhs } else { *self } } } pub fn chmax<T: PartialOrd+Clone>(a: &mut T, b: &T){ if *a < *b{ *a = b.clone(); } } pub fn chmin<T: PartialOrd+Clone>(a: &mut T, b: &T){ if *a > *b{ *a = b.clone(); } } pub fn gcd(mut a: i64, mut b: i64)->i64{ if b==0{return a;}(a,b)=(a.abs(),b.abs());while b!=0{ let c = a;a = b;b = c%b; }a } pub fn factorial_i64(n: usize)->(Vec<i64>, Vec<i64>){ let mut res = vec![1; n+1];let mut inv = vec![1; n+1];for i in 0..n{ res[i+1] = (res[i]*(i+1)as i64)%MOD; }inv[n] = mod_inverse(res[n], MOD);for i in (0..n).rev(){ inv[i] = inv[i+1]*(i+1) as i64%MOD; }(res, inv) } pub fn floor(a:i64, b:i64)->i64{let res=(a%b+b)%b;(a-res)/b} pub fn extended_gcd(a:i64,b:i64)->(i64,i64,i64) {if b==0{(a,1,0)}else{let(g,x,y)=extended_gcd(b,a%b);(g,y,x-floor(a,b)*y)}} pub fn mod_inverse(a:i64,m:i64)->i64{let(_,x,_) =extended_gcd(a,m);(x%m+m)%m} pub fn comb(a: i64, b: i64, f: &Vec<(i64, i64)>)->i64{ if a<b{return 0;}else if b==0 || a==b{ return 1; } else{let x=f[a as usize].0; let y=f[(a-b) as usize].1;let z=f[b as usize].1;return((x*y)%MOD)*z%MOD;}} pub fn factorial(x: i64)->Vec<(i64, i64)>{ let mut f=vec![(1i64,1i64),(1, 1)];let mut z = 1i64; let mut inv = vec![0; x as usize+10];inv[1] = 1; for i in 2..x+1{z=(z*i)%MOD; let w=(MOD-inv[(MOD%i)as usize]*(MOD/i)%MOD)%MOD; inv[i as usize] = w; f.push((z, (f[i as usize-1].1*w)%MOD));}return f;} pub fn fast_mod_pow(x: i64,p: usize, m: i64)->i64{ let mut res=1;let mut t=x;let mut z=p;while z > 0{ if z%2==1{res = (res*t)%m;}t = (t*t)%m;z /= 2; }res} #[allow(unused_imports)] use std::{ convert::{Infallible, TryFrom, TryInto as _}, fmt::{self, Debug, Display, Formatter,}, fs::{File}, hash::{Hash, Hasher}, iter::{Product, Sum}, marker::PhantomData, ops::{Add, AddAssign, Sub, SubAssign, Div, DivAssign, Mul, MulAssign, Neg, RangeBounds}, str::FromStr, sync::{atomic::{self, AtomicU32, AtomicU64}, Once}, collections::{*, btree_set::Range, btree_map::Range as BTreeRange}, mem::{swap}, cmp::{self, Reverse, Ordering, Eq, PartialEq, PartialOrd}, thread::LocalKey, f64::consts::PI, time::Instant, cell::RefCell, io::{self, stdin, Read, read_to_string, BufWriter, BufReader, stdout, Write}, }; #[allow(unused_imports)] use proconio::{input, input_interactive, marker::{*}}; #[allow(unused_imports)] //use rand::{thread_rng, Rng, seq::SliceRandom, prelude::*}; #[allow(unused_imports)] //use itertools::Itertools; #[allow(unused_imports)] //use ordered_float::OrderedFloat; #[allow(unused_imports)] //use ac_library::{*, ModInt998244353 as mint}; #[allow(dead_code)] //type MI = StaticModInt<Mod998244353>;pub fn factorial_mint(n: usize)->(Vec<MI>, Vec<MI>){ let mut res = vec![mint::new(1); n+1];let mut inv = vec![mint::new(1); n+1];for i in 0..n{res[i+1] = res[i]*(i+1);}inv[n] = mint::new(1)/res[n];for i in (0..n).rev(){inv[i] = inv[i+1]*(i+1);}(res, inv)} #[allow(dead_code)] const INF: i64 = 1<<60; #[allow(dead_code)] const MOD: i64 = 998244353; #[allow(dead_code)] const D: [(usize, usize); 4] = [(1, 0), (0, 1), (!0, 0), (0, !0)]; #[allow(dead_code)] const D2: [(usize, usize); 8] = [(1, 0), (1, 1), (0, 1), (!0, 1), (!0, 0), (!0, !0), (0, !0), (1, !0)]; #[derive(Default)] pub(crate) struct SimpleQueue<T> { payload: Vec<T>, pos: usize, } impl<T> SimpleQueue<T> { pub(crate) fn reserve(&mut self, n: usize) { if n > self.payload.len() { self.payload.reserve(n - self.payload.len()); } } pub(crate) fn size(&self) -> usize { self.payload.len() - self.pos } pub(crate) fn empty(&self) -> bool { self.pos == self.payload.len() } pub(crate) fn push(&mut self, t: T) { self.payload.push(t); } // Do we need mutable version? pub(crate) fn front(&self) -> Option<&T> { if self.pos < self.payload.len() { Some(&self.payload[self.pos]) } else { None } } pub(crate) fn clear(&mut self) { self.payload.clear(); self.pos = 0; } pub(crate) fn pop(&mut self) -> Option<&T> { if self.pos < self.payload.len() { self.pos += 1; Some(&self.payload[self.pos - 1]) } else { None } } } use std::{ ops::{ BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, }, }; // Skipped: // // - `is_signed_int_t<T>` (probably won't be used directly in `modint.rs`) // - `is_unsigned_int_t<T>` (probably won't be used directly in `modint.rs`) // - `to_unsigned_t<T>` (not used in `fenwicktree.rs`) /// Corresponds to `std::is_integral` in C++. // We will remove unnecessary bounds later. // // Maybe we should rename this to `PrimitiveInteger` or something, as it probably won't be used in the // same way as the original ACL. pub trait Integral: 'static + Send + Sync + Copy + Ord + Not<Output = Self> + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + Rem<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign + Sum + Product + BitOr<Output = Self> + BitAnd<Output = Self> + BitXor<Output = Self> + BitOrAssign + BitAndAssign + BitXorAssign + Shl<Output = Self> + Shr<Output = Self> + ShlAssign + ShrAssign + fmt::Display + fmt::Debug + fmt::Binary + fmt::Octal + Zero + One + BoundedBelow + BoundedAbove { } /// Class that has additive identity element pub trait Zero { /// The additive identity element fn zero() -> Self; } /// Class that has multiplicative identity element pub trait One { /// The multiplicative identity element fn one() -> Self; } pub trait BoundedBelow { fn min_value() -> Self; } pub trait BoundedAbove { fn max_value() -> Self; } macro_rules! impl_integral { ($($ty:ty),*) => { $( impl Zero for $ty { #[inline] fn zero() -> Self { 0 } } impl One for $ty { #[inline] fn one() -> Self { 1 } } impl BoundedBelow for $ty { #[inline] fn min_value() -> Self { Self::MIN } } impl BoundedAbove for $ty { #[inline] fn max_value() -> Self { Self::MAX } } impl Integral for $ty {} )* }; } impl_integral!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize); use std::cmp::min; use std::iter; impl<Cap> MfGraph<Cap> where Cap: Integral, { pub fn new(n: usize) -> MfGraph<Cap> { MfGraph { _n: n, pos: Vec::new(), g: iter::repeat_with(Vec::new).take(n).collect(), } } pub fn add_edge(&mut self, from: usize, to: usize, cap: Cap) -> usize { assert!(from < self._n); assert!(to < self._n); assert!(Cap::zero() <= cap); let m = self.pos.len(); self.pos.push((from, self.g[from].len())); let rev = self.g[to].len() + usize::from(from == to); self.g[from].push(_Edge { to, rev, cap }); let rev = self.g[from].len() - 1; self.g[to].push(_Edge { to: from, rev, cap: Cap::zero(), }); m } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Edge<Cap: Integral> { pub from: usize, pub to: usize, pub cap: Cap, pub flow: Cap, } impl<Cap> MfGraph<Cap> where Cap: Integral, { pub fn get_edge(&self, i: usize) -> Edge<Cap> { let m = self.pos.len(); assert!(i < m); let _e = &self.g[self.pos[i].0][self.pos[i].1]; let _re = &self.g[_e.to][_e.rev]; Edge { from: self.pos[i].0, to: _e.to, cap: _e.cap + _re.cap, flow: _re.cap, } } pub fn edges(&self) -> Vec<Edge<Cap>> { let m = self.pos.len(); (0..m).map(|i| self.get_edge(i)).collect() } pub fn change_edge(&mut self, i: usize, new_cap: Cap, new_flow: Cap) { let m = self.pos.len(); assert!(i < m); assert!(Cap::zero() <= new_flow && new_flow <= new_cap); let (to, rev) = { let _e = &mut self.g[self.pos[i].0][self.pos[i].1]; _e.cap = new_cap - new_flow; (_e.to, _e.rev) }; let _re = &mut self.g[to][rev]; _re.cap = new_flow; } /// `s != t` must hold, otherwise it panics. pub fn flow(&mut self, s: usize, t: usize) -> Cap { self.flow_with_capacity(s, t, Cap::max_value()) } /// # Parameters /// * `s != t` must hold, otherwise it panics. /// * `flow_limit >= 0` pub fn flow_with_capacity(&mut self, s: usize, t: usize, flow_limit: Cap) -> Cap { let n_ = self._n; assert!(s < n_); assert!(t < n_); // By the definition of max flow in appendix.html, this function should return 0 // when the same vertices are provided. On the other hand, it is reasonable to // return infinity-like value too, which is what the original implementation // (and this implementation without the following assertion) does. // Since either return value is confusing, we'd rather deny the parameters // of the two same vertices. // For more details, see https://github.com/rust-lang-ja/ac-library-rs/pull/24#discussion_r485343451 // and https://github.com/atcoder/ac-library/issues/5 . assert_ne!(s, t); // Additional constraint assert!(Cap::zero() <= flow_limit); let mut calc = FlowCalculator { graph: self, s, t, flow_limit, level: vec![0; n_], iter: vec![0; n_], que: SimpleQueue::default(), }; let mut flow = Cap::zero(); while flow < flow_limit { calc.bfs(); if calc.level[t] == -1 { break; } calc.iter.iter_mut().for_each(|e| *e = 0); while flow < flow_limit { let f = calc.dfs(t, flow_limit - flow); if f == Cap::zero() { break; } flow += f; } } flow } pub fn min_cut(&self, s: usize) -> Vec<bool> { let mut visited = vec![false; self._n]; let mut que = SimpleQueue::default(); que.push(s); while let Some(&p) = que.pop() { visited[p] = true; for e in &self.g[p] { if e.cap != Cap::zero() && !visited[e.to] { visited[e.to] = true; que.push(e.to); } } } visited } } struct FlowCalculator<'a, Cap> { graph: &'a mut MfGraph<Cap>, s: usize, t: usize, flow_limit: Cap, level: Vec<i32>, iter: Vec<usize>, que: SimpleQueue<usize>, } impl<Cap> FlowCalculator<'_, Cap> where Cap: Integral, { fn bfs(&mut self) { self.level.iter_mut().for_each(|e| *e = -1); self.level[self.s] = 0; self.que.clear(); self.que.push(self.s); while let Some(&v) = self.que.pop() { for e in &self.graph.g[v] { if e.cap == Cap::zero() || self.level[e.to] >= 0 { continue; } self.level[e.to] = self.level[v] + 1; if e.to == self.t { return; } self.que.push(e.to); } } } fn dfs(&mut self, v: usize, up: Cap) -> Cap { if v == self.s { return up; } let mut res = Cap::zero(); let level_v = self.level[v]; for i in self.iter[v]..self.graph.g[v].len() { self.iter[v] = i; let &_Edge { to: e_to, rev: e_rev, .. } = &self.graph.g[v][i]; if level_v <= self.level[e_to] || self.graph.g[e_to][e_rev].cap == Cap::zero() { continue; } let d = self.dfs(e_to, min(up - res, self.graph.g[e_to][e_rev].cap)); if d <= Cap::zero() { continue; } self.graph.g[v][i].cap += d; self.graph.g[e_to][e_rev].cap -= d; res += d; if res == up { return res; } } self.iter[v] = self.graph.g[v].len(); res } } #[derive(Clone, Debug, Default)] pub struct MfGraph<Cap> { _n: usize, pos: Vec<(usize, usize)>, g: Vec<Vec<_Edge<Cap>>>, } #[derive(Clone, Debug)] struct _Edge<Cap> { to: usize, rev: usize, cap: Cap, } const B: i64 = 1<<40; //use proconio::fastout; //#[fastout] fn main() { input!{ n: usize, p: [i64; n], m: usize, e: [(Usize1, Usize1); m], k: usize, s: [(Usize1, Usize1, i64); k], } let mut mf = MfGraph::new(n+k+2); let st = n+k; let end = n+k+1; let mut ans = 0; for (i, &v) in p.iter().enumerate(){ if v >= 0{ ans += v; mf.add_edge(st, i, v); mf.add_edge(i, end, 0); } else { mf.add_edge(st, i, 0); mf.add_edge(i, end, -v); } } for &(u, v) in &e{ mf.add_edge(v, u, B); } for (idx, &(u, v, add)) in s.iter().enumerate(){ let p = idx+n; mf.add_edge(st, p, add); mf.add_edge(p, u, B); mf.add_edge(p, v, B); ans += add; } println!("{}", ans-mf.flow(st, end)); }