3 solutions

  • 0
    @ 2026-8-7 11:14:53

    b (b.cpp) 标程深度学习:基于 BFS 层次图的最短路极限构造

    基础信息:提高(青) | BFS分层 / 构造 | O(N+M)O(N+M) 【隔离警告:严禁输出模式二的考点分析和策略!】

    1. 思路来源与取舍: 原作者在审视“删去所有权值为 xx 的边后,SS 和 TT 不连通”这一条件时,敏锐地抓住了最短路这一核心性质。 任何一条从 SS 到 TT 的合法路径,要能经受住 kk 次不同颜色的轮番轰炸(每次删去颜色 x∈[1,k]x \in [1, k] 的边),就意味着这条路径上必须同时包含颜色 1,2,…,k1, 2, \dots, k 的所有边。 因此,从 SS 到 TT 的最短路径长度 dist(S,T)dist(S,T),就是 kk 的绝对理论上限!因为如果你令 k>dist(S,T)k > dist(S,T),那条最短路上根本凑不齐 kk 种颜色,必然在某次删除操作中“幸存”,从而导致 S,TS,T 依然连通。 思路破局后,取舍就非常直接:通过 BFS 建立从 SS 出发的“等高线”(层次图),强制要求任意跨越两层的边带有对应的深度颜色,把构造过程简化为直接拿节点的深度求 max。

    2. 核心代码掰开揉碎讲: 代码的核心精髓浓缩在 max(dist[i], dist[j]) 这一句。

    • 大白话把变量“焊死”:dist[i] 就是点 ii 在 BFS 树中距离起点 SS 的步数。
    • 为什么取 max 就能构造出完美的割? 考虑任意一条从 SS 出发前往 TT 的路径,起点的 dist=0dist=0,终点的 dist=kdist=k。 在图上每走一步(走过一条边),由于图的连通性质,相连两个节点的 distdist 差值绝对不会超过 1。这意味着,要从 0 爬到 kk,这根路径上的点必然会依次经历 dist≥1,≥2,…,≥kdist \ge 1, \ge 2, \dots, \ge k 的历史时刻! 当这根路径试图从深度 x−1x-1 的区域迈向深度 xx (或更深)的区域时,必然通过一条边 (u,v)(u, v)。这条边的 max(dist[u], dist[v]) 恰好就是 xx! 这就从数学上焊死了:任何一条 S→TS \to T 的路径,必定包含至少一条权值为 xx 的边。所以一旦删掉所有标号为 xx 的边,S→TS \to T 的联系就会被彻底切断。
    • 为什么需要判定 dist[i]>dist[t] || dist[j]>dist[t]? 因为题目只要求切断 S→TS \to T,比 TT 还远的节点构成的网络(dist>kdist > k)属于“无关紧要的后方”。对这些后方边赋 00 完美规避了干扰(权值为 00 的边不会被删)。
    1. 代码架构与底层细节:
    • 缺省源与 I/O:原作者大量使用了 #define int long long 和快速宏,这种工程写法在比赛中能极大加速代码产出。cin.tie(0) 关闭了同步流,属于标准卡常手笔。
    • 空间极其节约:不需要保存边权数组,在跑完 BFS 之后直接在遍历 EE 的过程中计算并打印答案,做到了 O(1)O(1) 的额外空间开销,展现了极简的工程美感。
    1. 工程还原与调试推演:
    • 考场上搭积木的过程必然是:先建图 →\to 初始化 dist 数组全为 −1-1 →\to 标准队列 BFS 出每个点离 SS 的最短距离。
    • 接着调试样例:以样例 1 为例,S=1,T=4S=1, T=4。 dist[1]=0, dist[2]=1, dist[3]=1, dist[4]=2。最短路 k=2k=2。 边 (1,4) 直达但不存在,边 (1,2) 取 max(0,1) = 1,边 (1,3) 取 max(0,1) = 1。 边 (2,4) 取 max(1,2) = 2,边 (3,4) 取 max(1,2) = 2。 边 (2,3) 同层取 max(1,1) = 1。 输出直接契合逻辑!
    • 至于未连通的点(dist=−1dist=-1),直接拦截赋 00,兜底了所有边界恶心情况。
    1. 适用场景与死穴:
    • 死穴 1:endl 的滥用导致 I/O 阻塞。 代码中在遍历输出边权时使用了 cout << ... << endl;。在最坏情况下 M=2×105M = 2 \times 10^5,执行如此多次数的清空缓冲区会导致常数巨大,线上评测极有可能卡掉 2.0s 的时限。必须替换为 '\n'!
    • 适用场景:所有形如“交集最小割”、“多重阻断”的无权图问题,只要涉及到路径长度与切断条件的耦合,优先无脑上 BFS 层次图!
    1. 带详尽注释的完整代码:
    /*
     *                                                     __----~~~~~~~~~~~------___
     *                                    .  .   ~~//====......          __--~ ~~
     *                    -.            \_|//     |||\\  ~~~~~~::::... /~
     *                 ___-==_       _-~o~  \/    |||  \\            _/~~-
     *         __---~~~.==~||\=_    -_--~/_-~|-   |\\   \\        _/~
     *     _-~~     .=~    |  \\-_    '-~7  /-   /  ||    \      /
     *   .~       .~       |   \\ -_    /  /-   /   ||      \   /
     *  /  ____  /         |     \\ ~-_/  /|- _/   .||       \ /
     *  |~~    ~~|--~~~~--_ \     ~==-/   | \~--===~~        .\
     *           '         ~-|      /|    |-~\~~       __--~~
     *                       |-~~-_/ |    |   ~\_   _-~            /\
     *                            /  \     \__   \/~                \__
     *                        _--~ _/ | .-~~____--~-/                  ~~==.
     *                       ((->/~   '.|||' -_|    ~~-/ ,              . _||
     *                                  -_     ~\      ~~---l__i__i__i--~~_/
     *                                  _-~-__   ~)  \--______________--~~
     *                                //.-~~~-~_--~- |-------~~~~~~~~
     *                                       //.-~~~--\
     *                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     *                               神兽保佑            永无BUG
     */
    
    /*
     * @Description: I want to be the weakest vegetable in the world!
     * @Author: I.Z.
     */
    #include<bits/stdc++.h>
    using namespace std;
    #define MOD         998244353
    #define speMOD      2933256077ll
    #define int         long long
    #define pii         pair<int,int>
    #define all(v)      v.begin(),v.end()
    #define pb          push_back
    #define REP(i,b,e)  for(int i=(b);i<(int)(e);++i)
    #define over(x)     {cout<<(x)<<endl;return;}
    #define lowbit(x)   ((x)&(-(x)))
    #define cntbit(x)   __builtin_popcount(x)
    #define rf(v)       shuffle(all(v),sd);
    #define deal(v)     sort(all(v));v.erase(unique(v.begin(),v.end()),v.end())
    #define lbound(v,x) lower_bound(all(v),x)-v.begin()
    mt19937 sd(random_device{}());
    int qpow(int a,int b,int m=MOD,int res=1){
    	a%=m;
    	while(b>0)res=(b&1)?(res*a%m):(res),a=a*a%m,b>>=1;
    	return res;
    }
    string YN(bool x,string Y="Yes",string N="No") {
    	if(x){
    		return Y;
    	} else {
    		return N;
    	}
    }
    int exgcd(int x,int y,int &a,int &b){
    	if(y==0){
    		a=1;b=0;
    		return x;
    	}
    	int d=exgcd(y,x%y,a,b);
    	int z=b;
    	b=a-b*(x/y);
    	a=z;
    	return d;
    }
    int _x_,_y_;
    inline int inverse(int x,int y=MOD){
    	exgcd(x,y,_x_,_y_);
    	return (_x_+y)%y;
    }
    int fac[2000005],inv[2000005];
    void init(int n){
    	fac[0]=inv[0]=1;
    	REP(i,1,n+1)fac[i]=fac[i-1]*i%MOD;
    	inv[n]=qpow(fac[n],MOD-2);
    	for(int i=n-1;i>=1;--i)inv[i]=inv[i+1]*(i+1)%MOD;
    }
    int binom(int x,int y){
    	return x<y||y<0? 0:fac[x]*inv[y]%MOD*inv[x-y]%MOD;
    }
    int n,m,s,t;
    vector<int>v[405];
    vector<pii>E;
    int dist[405];
    void Main() {
    	cin>>n>>m>>s>>t;
    	--s,--t; // 顶点映射为 0-based
    	REP(i,0,m){
    		int x,y;
    		cin>>x>>y;
    		--x,--y;
    		E.pb({x,y}); // 存下所有的边供后续顺序输出权值使用
    		v[x].pb(y);
    		v[y].pb(x);
    	}
    	
    	// 初始化所有点的距离为 -1
    	REP(i,0,n) dist[i]=-1;
    	queue<int>q;
    	q.push(s);
    	dist[s]=0; // 起点距离焊死为 0
    	
    	// 核心步骤:BFS 跑层次图最短路
    	while(!q.empty()){
    		int x=q.front();
    		q.pop();
    		for(auto i:v[x]){
    			if(dist[i]==-1){
    				dist[i]=dist[x]+1;
    				q.push(i);
    			}
    		}
    	}
    	
    	// S 到 T 的最短路长度即为最大的 k
    	cout<<dist[t]<<endl;
    	
    	for(auto e:E){
    		int i=e.first, j=e.second;
    		// 边界兜底:如果是死胡同不连通的点,或者是深度超过目标 T 的多余后方边
    		if(dist[i]==-1 || dist[j]==-1) cout<<0<<endl;
    		else if(dist[i]>dist[t] || dist[j]>dist[t]) cout<<0<<endl; // 这些边赋 0,不参与阻断
    		// 否则赋予深度的较大值作为该边的染色!
    		else cout<<max(dist[i],dist[j])<<endl; 
    	}
    }
    void TC() {
        int tc=1;
    	while(tc--){
    		Main();
    		cout.flush();
    	}
    }
    signed main() {
    	// 文件操作被原作者保留,符合自适应协议
    	freopen("b.in","r",stdin);
    	freopen("b.out","w",stdout);
    	return cin.tie(0),cout.tie(0),ios::sync_with_stdio(0),TC(),0;
    }
    
    1. 核心 Trick 与通用技巧(高亮警告): 【高亮警告 1:图的层次化切分法则】 凡是在无权图上探讨“覆盖”、“切断”类路径问题,一旦要求具有某种阶梯性质(比如逐步删去 1∼k1 \sim k 都要断),永远第一时间往 BFS 最短路树(层次图) 上靠!层次图中跨层边的 max⁡\max 属性自带天然的完备截断性(任何从 0 到 kk 的连续状态机必定触犯至少一次状态 xx),这是算法竞赛中极高维的构造套路!

    【高亮警告 2:多测中的 I/O 防爆策略】 不要在循环体中高频使用 endl!本题虽然只有一组测试数据,但在常规的多测数据(如 T=10,∑M≤2×105T=10, \sum M \le 2\times10^5)中,这 2020 万次 endl 会触发 2020 万次操作系统的 Flush 系统调用,直接导致耗时激增 5 倍以上!强制养成在循环输出内部使用 '\n',仅在需要清空缓冲区时(如交互题、输出大段结束)使用 endl 或 flush() 的习惯。

    • 0
      @ 2026-8-3 19:14:16

      b:最短路径与不交割的拓扑对偶

      基础信息:普及+/提高(绿题) | 复杂度极限 O(N+M)O(N+M) | 算法标签:图论、BFS分层图、最小路径最大割对偶

      1. 这题在考啥 & 常规套路

      这题披着“给边赋权”的外衣,本质上在考查图论中极度经典的最小路径与最大不交割(Min-Path Max-Cut)对偶定理。题目要求划分出 kk 个互不相交的边集,且每个边集都是一个能切断 SS 和 TT 连通性的“割”。

      2. 怎么想到的 (How & Why)

      如果考场上你试图去枚举每一条边填什么权值,那 O(kM)O(k^M) 的搜索树连最基础的测试点都会爆零。 我们必须从“割”的物理意义去降维打击:如果存在 kk 个互不相交的割,那么任意一条从 SS 到 TT 的路径,都必须穿越这 kk 个割的每一个。因为割互不相交(一条边只能有一种权值),这意味着这条路径必定至少包含 kk 条边! 既然“任意一条路径长度 ≥k\ge k”,那最短路的长度也必然 ≥k\ge k。于是我们瞬间拿到了 kk 的绝对天花板:k≤d(S,T)k \le d(S, T)。

      怎么达到这个天花板?BFS! 以 SS 为源点跑 BFS 分层图,第 x−1x-1 层到第 xx 层的连边,天然就构成了一个完美的割!而且因为 BFS 的相邻节点深度差最多为 1,不同层之间的跨层边绝对不可能在物理上产生交集。我们直接把 kk 焊死在最短路长度上,用 BFS 层级去给边涂色即可!

      3. 核心算法与“焊死”变量定义

      • dist[v]:点 vv 到源点 SS 的无权最短路径长度。
      • k:上限天花板,焊死为 dist[T]。
      • 转移方程与涂色法则:对于原图的任意一条边 (u, v):
        1. 只要 abs(dist[u] - dist[v]) == 1,说明这条边是跨越两个相邻 BFS 层的桥梁,将其权值赋值为 x = max(dist[u], dist[v])。
        2. 铁律截断:如果算出的层级 x > k(即在 TT 之后的层级起到的隔离作用),或者这是一条同层连边 dist[u] == dist[v],它们对切断 S→TS \to T 毫无贡献,全部无脑赋为 0(题目允许多余的边权为 0 且永不被校验)。

      4. 时空复杂度与手推样例

      • 时空复杂度:O(N+M)O(N+M) 的纯 BFS。在 N=400,M≤80000N=400, M \le 80000 的数据规模面前就是零头,耗时 <5ms< 5\text{ms}。空间 O(N+M)O(N+M) 毫无压力。
      • 样例 1 推演:S=1,T=4S=1, T=4。BFS 后 d[1]=0,d[2]=1,d[3]=1,d[4]=2d[1]=0, d[2]=1, d[3]=1, d[4]=2。
        • 跨越 0-1 的边有 1-2 和 1-3,染为 1。
        • 跨越 1-2 的边有 2-4 和 3-4,染为 2。
        • 同层边 2-3 染为 0。 完美闭合,与样例输出分毫不差。

      5. 标程的工程构建与调试推演

      代码构建时,最关键的是离线存储边集。由于 BFS 遍历边的顺序和题目输入的顺序毫无关联,而在输出时必须严格遵照输入的 MM 条边的顺序给出权值。因此,一开始读图时,必须用 edges 数组按原样把边封存,等到 dist 全局落地后,再拿出来跑一遍判定。

      6. 考场必查的致命坑点

      • DFS 的误导:如果你图省事用 DFS 去求深度,图的层级会被彻底打乱,层与层之间的跨度可能 ≫1\gg 1,这会导致割的交错重叠,原本的对偶性质直接全盘崩溃!绝对且只能使用 BFS 求出最严谨的等高线!
      • 未达终点的不连通特判:本题虽然保证图连通,但在平时写这套板子时,若 dist[T] == -1,需直接特判 SS 和 TT 不连通输出 0。

      7. 极简完整代码与 I/O 抉择

      题目已明确给出了 b.in 和 b.out,绝不可删去 freopen。由于是无权图,直接采用原生队列实现。

      #include <bits/stdc++.h>
      
      using namespace std;
      
      int main() {
          // 强制关闭同步流,压榨 I/O 常数
          ios_base::sync_with_stdio(false);
          cin.tie(NULL);
          
          // 比赛铁律:严格遵守题目文件 I/O
          freopen("b.in", "r", stdin);
          freopen("b.out", "w", stdout);
      
          int n, m;
          if (!(cin >> n >> m)) return 0;
          
          int s, t;
          cin >> s >> t;
      
          vector<vector<int>> adj(n + 1);
          vector<pair<int, int>> edges(m + 1);
          
          for (int i = 1; i <= m; ++i) {
              int u, v;
              cin >> u >> v;
              adj[u].push_back(v);
              adj[v].push_back(u);
              edges[i] = {u, v}; // 封存边的原始输入顺序
          }
      
          // BFS 核心模块
          vector<int> dist(n + 1, -1);
          queue<int> q;
          
          dist[s] = 0;
          q.push(s);
      
          while (!q.empty()) {
              int u = q.front();
              q.pop();
      
              for (int v : adj[u]) {
                  if (dist[v] == -1) {
                      dist[v] = dist[u] + 1;
                      q.push(v);
                  }
              }
          }
      
          // 极限割数就是最短路长度
          int k = dist[t];
          cout << k << "\n";
      
          // 结算每一条边的归属涂色
          for (int i = 1; i <= m; ++i) {
              int u = edges[i].first;
              int v = edges[i].second;
              
              int w = 0;
              // 只有严格跨越相邻层的边才具备切断两层的“割”属性
              if (dist[u] != -1 && dist[v] != -1 && abs(dist[u] - dist[v]) == 1) {
                  int x = max(dist[u], dist[v]);
                  // 只保留 1~k 的有效隔离带,过远的层直接抛弃
                  if (x <= k) {
                      w = x;
                  }
              }
              cout << w << "\n";
          }
      
          return 0;
      }
      

      8. 核心 Trick 与通用技巧(高亮警告)

      💡 Trick:BFS 分层图的完美割属性

      永远记住,BFS 求出的不只是距离!它建立的 dist 数组,完美地将整个图划分为了一系列严格递增的等高线连通块。 在任何无向图中,“所有跨越 d=x−1d=x-1 到 d=xd=x 的边”必定构成一个将起点与外部绝对隔离的割集!无论后面的边怎么走,都不可能产生时光倒流绕开这条封锁线。这是解决一切无权图“最小割 / 路径阻断”构造题的降维核武器。

      • 0
        @ 2026-7-27 15:57:29
        
        
        /*
         *                                                     __----~~~~~~~~~~~------___
         *                                    .  .   ~~//====......          __--~ ~~
         *                    -.            \_|//     |||\\  ~~~~~~::::... /~
         *                 ___-==_       _-~o~  \/    |||  \\            _/~~-
         *         __---~~~.==~||\=_    -_--~/_-~|-   |\\   \\        _/~
         *     _-~~     .=~    |  \\-_    '-~7  /-   /  ||    \      /
         *   .~       .~       |   \\ -_    /  /-   /   ||      \   /
         *  /  ____  /         |     \\ ~-_/  /|- _/   .||       \ /
         *  |~~    ~~|--~~~~--_ \     ~==-/   | \~--===~~        .\
         *           '         ~-|      /|    |-~\~~       __--~~
         *                       |-~~-_/ |    |   ~\_   _-~            /\
         *                            /  \     \__   \/~                \__
         *                        _--~ _/ | .-~~____--~-/                  ~~==.
         *                       ((->/~   '.|||' -_|    ~~-/ ,              . _||
         *                                  -_     ~\      ~~---l__i__i__i--~~_/
         *                                  _-~-__   ~)  \--______________--~~
         *                                //.-~~~-~_--~- |-------~~~~~~~~
         *                                       //.-~~~--\
         *                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         *
         *                               神兽保佑            永无BUG
         */
        
        /*
         * @Description: I want to be the weakest vegetable in the world!
         * @Author: I.Z.
         */
        #include<bits/stdc++.h>
        using namespace std;
        #define MOD         998244353
        #define speMOD      2933256077ll
        #define int         long long
        #define pii         pair<int,int>
        #define all(v)      v.begin(),v.end()
        #define pb          push_back
        #define REP(i,b,e)  for(int i=(b);i<(int)(e);++i)
        #define over(x)     {cout<<(x)<<endl;return;}
        #define lowbit(x)   ((x)&(-(x)))
        #define cntbit(x)   __builtin_popcount(x)
        #define rf(v)       shuffle(all(v),sd);
        #define deal(v)     sort(all(v));v.erase(unique(v.begin(),v.end()),v.end())
        #define lbound(v,x) lower_bound(all(v),x)-v.begin()
        mt19937 sd(random_device{}());
        int qpow(int a,int b,int m=MOD,int res=1){
        	a%=m;
        	while(b>0)res=(b&1)?(res*a%m):(res),a=a*a%m,b>>=1;
        	return res;
        }
        string YN(bool x,string Y="Yes",string N="No") {
        	if(x){
        		return Y;
        	} else {
        		return N;
        	}
        }
        int exgcd(int x,int y,int &a,int &b){
        	if(y==0){
        		a=1;b=0;
        		return x;
        	}
        	int d=exgcd(y,x%y,a,b);
        	int z=b;
        	b=a-b*(x/y);
        	a=z;
        	return d;
        }
        int _x_,_y_;
        inline int inverse(int x,int y=MOD){
        	exgcd(x,y,_x_,_y_);
        	return (_x_+y)%y;
        }
        int fac[2000005],inv[2000005];
        void init(int n){
        	fac[0]=inv[0]=1;
        	REP(i,1,n+1)fac[i]=fac[i-1]*i%MOD;
        	inv[n]=qpow(fac[n],MOD-2);
        	for(int i=n-1;i>=1;--i)inv[i]=inv[i+1]*(i+1)%MOD;
        }
        int binom(int x,int y){
        	return x<y||y<0? 0:fac[x]*inv[y]%MOD*inv[x-y]%MOD;
        }
        int n,m,s,t;
        vector<int>v[405];
        vector<pii>E;
        int dist[405];
        void Main() {
        	cin>>n>>m>>s>>t;--s,--t;
        	REP(i,0,m){
        		int x,y;
        		cin>>x>>y;
        		--x,--y;E.pb({x,y});
        		v[x].pb(y);v[y].pb(x);
        	}
        	REP(i,0,n)dist[i]=-1;
        	queue<int>q;q.push(s);
        	dist[s]=0;
        	while(!q.empty()){
        		int x=q.front();q.pop();
        		for(auto i:v[x])if(dist[i]==-1){
        			dist[i]=dist[x]+1;
        			q.push(i);
        		}
        	}
        	cout<<dist[t]<<endl;
        	for(auto e:E){
        		int i=e.first,j=e.second;
        		if(dist[i]==-1||dist[j]==-1)cout<<0<<endl;
        		else if(dist[i]>dist[t]||dist[j]>dist[t])cout<<0<<endl;
        		else cout<<max(dist[i],dist[j])<<endl;
        	}
        }
        void TC() {
            int tc=1;
        	while(tc--){
        		Main();
        		cout.flush();
        	}
        }
        signed main() {
        	freopen("b.in","r",stdin);
        	freopen("b.out","w",stdout);
        	return cin.tie(0),cout.tie(0),ios::sync_with_stdio(0),TC(),0;
        }
        /*
        1. CLEAR the arrays (ESPECIALLY multitests)
        2. DELETE useless output
         */
        
        • 1

        Information

        ID
        2840
        Time
        2000ms
        Memory
        512MiB
        Difficulty
        10
        Tags
        (None)
        # Submissions
        2
        Accepted
        2
        Uploaded By