跳到正文

休闲·娱乐

efzzz 信竞娱乐赛题解

ACpigz约 50 分钟
原文
文章信息与版本

文章信息

发布
2025年11月28日
收录
2025年12月12日
更新
2026年9月23日
篇幅
约 50 分钟

版本

  1. v9当前
  2. v8
  3. v7
  4. v6
更早的 5 个版本
  1. v5
  2. v4
  3. v3
  4. v2
  5. v1

算法提示:

题号题可行算法(可能有别的解法)
A生物限时练习并查集/图连通分量统计
B英语限时练习A记忆化搜索/dp/拓扑排序
C物理限时练习A模拟
D地理限时练习A优先队列BFS
E数学限时练习Adp
F、G\red{F、G}数学限时练习B最短路/贪心/拓扑、二分/多源BFS(存疑)
H英语限时练习B费用流/二分图匹配
I化学限时练习A模拟、高斯消元
J语文限时练习AKMP/dp
K化学限时练习Bluogu搜索烷烃计数

F、G\red{F、G} 暂无完备题解,数据也很水

题解:(欢迎找茬)

A:\bold{A:} 生物限时练习

题目分析

这是一个典型的连通分量计数问题。我们需要找出所有通过相似关系连接的生物样本组,每组属于同一物种,最后统计不同组的数量。

解题思路

使用 并查集 数据结构可以高效解决这个问题:

  1. 初始化:每个样本初始时各自为一个独立的集合
  2. 合并操作:对于每对相似关系,将两个样本所在的集合合并
  3. 统计结果:最后统计有多少个不同的集合(即根节点的数量)

并查集优化

为了达到较低的时间复杂度,我们采用:

  • 路径压缩:在查找时扁平化树结构
  • 按秩合并:将较小的树合并到较大的树下

代码实现

C++
#include<iostream>
using namespace std;

const int maxn=1e5+9;

int n,m;
int fa[maxn],siz[maxn];
int cnt;

int get_fa(int x){
	return (fa[x]==x? x:fa[x]=get_fa(fa[x]));
}
void merge(int x,int y){
	x=get_fa(x);
	y=get_fa(y);
	if(x==y) return;
	if(siz[x]>siz[y]) swap(x,y);
	fa[x]=y;
	siz[y]+=x;
	siz[x]=0;
	cnt--;
}


int main(){
	cin>>n>>m;
	cnt=n;
	for(int i=1;i<=n;i++){
		fa[i]=i;
		siz[i]=1;
	}
	for(int i=1;i<=m;i++){
		int g,k;
		cin>>g>>k;
		merge(g,k);
	}
	cout<<cnt<<endl;
}

算法复杂度

  • 时间复杂度: O(m×α(n))O(m \times α(n)) ,其中 αα 是反阿克曼函数,对于实际应用可以认为是常数时间
  • 空间复杂度: O(n)O(n)

关键点

  • 并查集能够高效处理具有传递性的等价关系
  • 路径压缩和按秩合并保证了接近线性的时间复杂度
  • 最终集合数量就是不同物种的数量

B:\bold{B:} 英语限时练习

这是一个三维嵌套问题,需要找到最长的箱子嵌套序列。每个箱子有长、宽、高三个维度,一个箱子能装下另一个箱子当且仅当存在一种旋转方式,使得前者的三个维度都严格大于后者的对应维度。

以题目中给出的样例2为例,我们可以构建一个如下的DAG。

解法一:记忆化搜索

算法思想

这种题目想到搜索是非常自然的事情。对于一个箱子,使用DFS的方法找出所有可能路径中最长的一条。但很可惜,直接DFS会TLE。

记忆化搜索给了深度优先搜索(DFS)增加了剪枝,通过递归方式探索所有可能的嵌套路径,同时保存已计算的结果避免重复计算。

详细步骤

  1. 数据预处理:

    • 对每个箱子的三个维度进行排序,统一表示形式
    • 这样每个箱子只有一种标准表示,便于比较
  2. 构建递归函数:

    C++
    int dfs(int u)  // 从箱子u开始的最长嵌套序列长度
  3. 递归过程:

    • 如果当前箱子的结果已计算,直接返回
    • 否则,遍历所有其他箱子,找到能被当前箱子装下的箱子
    • 递归计算这些箱子的最长序列,取最大值
  4. 终止条件:

    • 当没有箱子能被当前箱子装下时,返回1(只包含自己)

复杂度分析

  • 时间复杂度:O(n2),每个节点最多被计算一次,每次计算需要遍历所有其他节点
  • 空间复杂度:O(n),用于存储记忆化数组和递归栈

AC代码

C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;

struct Box {
    int x, y, z;
};

vector<Box> boxes;
vector<int> memo;

// 检查box1是否能装下box2
bool canContain(const Box& a, const Box& b) {
    return a.x > b.x && a.y > b.y && a.z > b.z;
}

int dfs(int u) {
    if (memo[u] != -1) return memo[u];

    int maxDepth = 1;
    for (int v = 0; v < boxes.size(); v++) {
        if (canContain(boxes[u], boxes[v])) {
            maxDepth = max(maxDepth, dfs(v) + 1);
        }
    }

    return memo[u] = maxDepth;
}

int main() {
    int n;
    cin >> n;

    boxes.resize(n);
    memo.resize(n, -1);

    for (int i = 0; i < n; i++) {
        cin >> boxes[i].x >> boxes[i].y >> boxes[i].z;
        // 对每个箱子的维度排序,便于比较
        vector<int> dims = {boxes[i].x, boxes[i].y, boxes[i].z};
        sort(dims.begin(), dims.end());
        boxes[i].x = dims[0];
        boxes[i].y = dims[1];
        boxes[i].z = dims[2];
    }

    int result = 0;
    for (int i = 0; i < n; i++) {
        result = max(result, dfs(i));
    }

    cout << result << endl;
    return 0;
}
一点点小优化

使用 sort 预先排序数据,每次只访问前面的,可以将时间开销减少一半。

解法二:动态规划

算法思想

动态规划通过自底向上的方式,利用已解决的子问题来构建更大问题的解。

详细步骤

  1. 数据预处理:

    • 同样对每个箱子的维度排序标准化
    • 将所有箱子按体积或字典序排序
  2. 状态定义:

    C++
    dp[i] = 以第i个箱子为最外层的最长嵌套序列长度
  3. 状态转移方程:

    代码
    dp[i] = max{ dp[j] + 1 } for all j where box[i] can contain box[j]
  4. 计算顺序:

    • 按排序后的顺序计算,确保在计算dp[i]时,所有可能的子问题dp[j](j < i)都已计算

复杂度分析

  • 时间复杂度:O(n2),双重循环比较所有箱子对
  • 空间复杂度:O(n),存储dp数组

代码实现要点

C++
// 按体积排序
sort(boxes.begin(), boxes.end(), [](const Box& a, const Box& b) {
    if (a.x != b.x) return a.x < b.x;
    if (a.y != b.y) return a.y < b.y;
    return a.z < b.z;
});

vector<int> dp(n, 1);
for (int i = 0; i < n; i++) {
    for (int j = 0; j < i; j++) {
        if (boxes[i].x > boxes[j].x &&
            boxes[i].y > boxes[j].y &&
            boxes[i].z > boxes[j].z) {
            dp[i] = max(dp[i], dp[j] + 1);
        }
    }
}

优势与适用场景

  • 优势:代码简洁,运行效率稳定,无递归开销
  • 适用场景:问题具有明显的最优子结构,数据规模较大时

你看,小的箱子一定要放到大箱子里,这不就是拓扑排序嘛!

关于第二题 acpigzacpigz 锐评没必要用图做但是我还是用拓扑排序做出来了()


拓扑排序的一个思想就是先把前面的所有必备的前置条件全都处理好再处理这个节点,那不就是和装箱子这个问题差不多嘛。

我们可以从大箱子向可以装进去的小箱子连边,这样对于任意的箱子,若要处理它,就需要处理前面的所有与它有关的“箱子链”。并且很有趣的是,因为按拓扑序来,我们可以知道前面所有箱子链的最优解(即最长链),这样再加上该箱子,其仍然为当前箱子经过链的最优解。所以我们证明了其正确性。

代码如下:

C++
#include <bits/stdc++.h>
using namespace std;

int a[2020][10];
int n,idx,ans;
vector<int> g[2020];
int in[2020],vis[2020];
queue<int> q;

int main(){
	cin>>n;
	for (int i=1;i<=n;i++){
		cin>>a[i][1]>>a[i][2]>>a[i][3];
		sort(a[i]+1,a[i]+4);
		for (int j=1;j<=i-1;j++){
			if (a[i][1]>a[j][1] and a[i][2]>a[j][2] and a[i][3]>a[j][3]){
				g[j].push_back(i);
				in[i]++;
			}
			if (a[i][1]<a[j][1] and a[i][2]<a[j][2] and a[i][3]<a[j][3]){
				g[i].push_back(j);
				in[j]++;
			}
		}
	}

	for (int i=1;i<=n;i++){
		if (not in[i]){
			q.push(i);
			vis[i]=1;
		}
	}

	while (!q.empty()){
		idx=q.front();
		q.pop();
		for (int x:g[idx]){
			in[x]--;
			if (not in[x]){
				q.push(x);
			}
			vis[x]=max(vis[x],vis[idx]+1);
		}
	}

	ans=0;
	for (int i=1;i<=n;i++){
		ans=max(ans,vis[i]);
	}
	cout<<ans;
}

C:\bold{C:} 物理限时练习A

不可以总司令(我觉得这道题目和OI就没啥关系)

这道题目本质上其实就是一道几何题。

因为题目问了结束时偏上还是偏下,我们不难先搞可以记进入磁场时的偏转角为 θθ ,θ>0θ>0 则偏上,θ<0θ<0 则偏下。

那么我们不妨画个图

不难证明出弦切角等于半圆心角。

那么很明显,要判断每一次正电荷能不能通过磁场,实际上是在判断 r×(1+sinθ)r\times{(1+sinθ)} 和 dd 的大小关系。r×(1+sinθ)>dr\times{(1+sinθ)} > d 则可以通过。而对于每一个磁场来说只需要判断一次即可,复杂度显然是 O(N) O(N) 的


然后我们可以继续看第二个问题

要求磁场中的时间−>要求周期−>要求圆心角−>θ+α要求磁场中的时间->要求周期->要求圆心角->θ+α

而 θθ 和 αα 前面显然是容易求得的 (其实也可以用 ∣θ初−θ末∣|θ_初 - θ_末| 直接求)

而 T=2πmqBT = \frac{2\pi m}{qB},所以 t=θ2π×2πmqB=θmqBt=\frac{θ}{2\pi}\times \frac{2\pi m}{qB} = \frac{θ m}{qB},而 tt 也能通过遍历一遍磁场累加,时间复杂度也为 O(N)O(N)。


第三个问题直接看最后 θ 的值,所以这个问题就这么解决了。

AC code:

C++
#include <bits/stdc++.h>
using namespace std;
double n,m,v,q,d,b,theta,new_theta,t,r;
int op;

double judge(){
	if (r*(1+sin(theta))<=d){
		cout<<"no";
		exit(0);
	}

	return asin((r*sin(theta)-d)/r);
}

int main(){
	cin>>n>>m>>v>>q;
	theta=0;
	for (int i=1;i<=n;i++){
		scanf("%d%lf%lf",&op,&d,&b);
		r=(1.0*m*v)/(1.0*q*b);
		if (op==0){
			new_theta=judge();
			t+=abs(new_theta-theta)*m*0.1/(q*b*0.1);
			theta=new_theta;
		}else{
			theta=-theta;
			new_theta=judge();
			t+=abs(new_theta-theta)*m*0.1/(q*b*0.1);
			theta=-new_theta;
		}
	}
	cout<<"yes\n";
	cout<<t<<"\n";
	if (theta>=0){
		cout<<"u\n";
	}else{
		cout<<"d\n";
	}
}

D:\bold{D:} 地理限时练习A

注意到反向从小明位置开始涨水更容易做。

使用priority queue进行BFS:

先将小明位置与其高度组成的变量插入优先队列,优先队列按照高度升序排列这些地块,

每次涨1高的水,判断优先队列队头是否被淹没,

若被淹没则将其四周未被淹没的地块加入优先队列,自己弹出队列,同时统计ans。重复直到优先队列为空或队首地块在水面上。

将每秒答案都记录在数组中,最后倒着输出即可

还没懂可以查看 Sinking Land 题解,思路类似。

AC code:

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,x,y,h;
int mp[1005][1005];
int flag[1005][1005]={0};
int xm[4]={0,0,1,-1};
int ym[4]={1,-1,0,0};
int ans[5005]={0};
int num=0;
struct node{
	int x;
	int y;
	int height;
	friend bool operator < (node x,node y)
	{
		return x.height>y.height;
	}
};
priority_queue<node> q;
int t=0;
signed main()
{
	memset(ans,0,sizeof(ans));
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m>>x>>y>>h;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			cin>>mp[i][j];
		}
	}
	t=mp[x][y];
	flag[x][y]=1;
	q.push({x,y,mp[x][y]});
	num=0;
	while(!q.empty())
	{
		while(t<q.top().height)
		{
			t++;
			ans[t]+=ans[t-1];
		}
		int xnow=q.top().x;
		int ynow=q.top().y;
		int hnow=q.top().height;
		q.pop();
		ans[t]++;
		for(int i=0;i<=3;i++)
		{
			int xx=xnow+xm[i];
			int yy=ynow+ym[i];
			if(flag[xx][yy]) continue;
			if(xx<1||xx>n) continue;
			if(yy<1||yy>m) continue;
			q.push({xx,yy,mp[xx][yy]});
			flag[xx][yy]=1;
		}
	}
	cout<<0<<endl;
	for(int i=h-t-1;i>=1;i--)
	{
		cout<<ans[t]<<endl;
	}
	for(int i=t;i>=mp[x][y];i--)
	{
		cout<<ans[i]<<endl;
	}
	return 0;
}

E:\bold{E:} 数学限时练习A

对于第一个答案,我们只需要模拟从满血开始打,每次减去两把刀伤害的max,cnt计数即可

对于第二个答案,由于总血量 M≤107M \leq 10^7,可以 O(M)O(M) dp。令 dpi,jdp_{i,j} 表示 boss 剩余 ii 血时,有没有换过刀分别最小需要多少刀从初始态转移到。

j=0j=0 表示在用第一把刀, j=1j=1 表示已经换过刀。初始化 dp 数组为正无穷, 初始化dp[M][0] = 0。

ii 从 MM 到 11 遍历,若此时 dp[i][0] 不为正无穷,

则更新 dp[i-刀1伤害][0] 与 dp[i-刀2伤害][1] 的值(若越界则表示杀死了boss,更新答案) ;

若 dp[i][1] 不为正无穷则更新 dp[i-刀2伤害][1] (越界同上更新答案)

C++
dp[i-calc()][0]=min(dp[i-calc()][0], dp[i][0]+1);

ans一直取溢出量最大值即可

如果你在7和15号测试点出现RE、WA等情况,注意一刀就砍死的情况

AC code:

C++
#include <bits/stdc++.h>
using namespace std;
int n, m, x, y, t;
int dp[10000007][2];
int calc(int atk, float mult)
{
	return int(atk*(1.0+mult/1000.0));
}
int main ()
{
	memset(dp,0x3f,sizeof(dp));
	cin >> m >> n >> x >> y >> t;
	dp[m][0]=dp[m][1]=0;
	//0用第一把 1用第二把
	for (int i = m; i >= 1; i--)
	{;
		if (i-calc(n, (int(i*100.0/m)*x)*1.0) >= 1){
			dp[i-calc(n, (int(i*100.0/m)*x)*1.0)][0]=min(dp[i-calc(n, (int(i*100.0/m)*x)*1.0)][0], dp[i][0]+1);
		}
		if (i-calc(n, (100.0-int(i*100.0/m))*y*1.0) >= 1){
			dp[i-calc(n, (100.0-int(i*100.0/m))*y*1.0)][1]=min(dp[i-calc(n, (100.0-int(i*100.0/m))*y*1.0)][1],min(dp[i][0]+1, dp[i][1]+1));
		}
	}
	int k = m, type=0, ans1=0;
	while (k>0)
	{
		if(type==0)
			if (calc(n, (int(k*100.0/m)*x)) < calc(n, (100.0-int(k*100.0/m))*y))
				type=1;
		if (type==0) k-=calc(n, (int(k*100.0/m)*1.0*x));
		else k-=calc(n, (100.0-(int(k*100.0/m)*1.0))*y);
		ans1++;
	}
	cout << ans1 << ' ';
	int pos=0;
	for (int i = 1; i <= m; i++)
	{
		if (dp[i][0] < t || dp[i][1] < t)
		{
			pos=i;
			break;
		}
	}
	if (ans1 == 1)
	{
		cout << calc(n, (100*x)*1.0)-m;
		return 0;
	}
	cout << calc(n,(100-int(pos*1.0*100.0/m))*y)-pos;
	return 0;
}
// dp表示打到当前血量至少用多少步,后面的0 1表示是否已经换刀
// 因为在t-1此前能达到的最低非死亡血量在下一击的击穿值一定最大
// 至于第一个数,直接模拟。

H:\bold{H:} 英语限时练习B

这道题是我在出A时突发奇想想出来的题目,后来跟各路大神讨论了一下,认为这是一个最小费用最大流(Minimum Cost Maximum Flow, MCMF)问题。我们的目标是在满足嵌套约束的前提下,将所有箱子划分成若干条链(即堆叠),并使得所有链的首个箱子(即最外层箱子)的高度之和最小。

1. 问题分析与建模

1.1 嵌套关系与图构建

首先,我们定义箱子间的嵌套关系。对于箱子 i(xi,yi,zi)i(x_i, y_i, z_i) 和 j(xj,yj,zj)j(x_j, y_j, z_j),我们先将各自的三个维度排序,得到 Si=(i1,i2,i3)S_i=(i_1, i_2, i_3) 和 Sj=(j1,j2,j3)S_j=(j_1, j_2, j_3)。 箱子 ii 可以装箱子 jj (即存在有向边 i→ji \to j) 当且仅当 ik>jki_k > j_k 对 k=1,2,3k=1, 2, 3 都成立。 根据题意,“一个箱子里面只能放一个箱子”,这意味着在最终的路径覆盖中,每个箱子最多只能作为一条链的起点或中间节点一次,且只能作为另一条链的终点或中间节点一次。这与二分图匹配的约束一致。

1.2 高度与目标函数

如果箱子 BB 是某条链的起点(即它是最外层的箱子),则它对总高度的贡献是 HB=min⁡(xB,yB,zB)H_B = \min(x_B, y_B, z_B)。 设总共有 NN 个箱子。如果我们能找到一个包含 FF 个嵌套关系的匹配 MM,则总共会形成 k=N−Fk = N - F 条路径(即 kk 个暴露的箱子)。 我们希望最小化这 kk 个暴露箱子的高度之和 Hmin⁡=∑e∈EHeH_{\min} = \sum_{e \in E} H_e,其中 EE 是暴露箱子的集合。

令 Htotal=∑i=1NHiH_{\text{total}} = \sum_{i=1}^N H_i (所有箱子的高度和)。 如果箱子 jj 被嵌套了(即 j∈Nj \in N),那么 HjH_j 就被“节省”了。 Hmin⁡=Htotal−∑j∈NHj=Htotal−HsavedH_{\min} = H_{\text{total}} - \sum_{j \in N} H_j = H_{\text{total}} - H_{\text{saved}}. 为了最小化 Hmin⁡H_{\min},我们需要最大化 HsavedH_{\text{saved}} (被嵌套箱子的高度之和) 和最大化匹配数 FF (优先)。

1.3 转化为 MCMF

我们构建一个二分图 G′=(VL∪VR,E′)G' = (V_L \cup V_R, E'),其中 VLV_L 和 VRV_R 都是 NN 个箱子的副本。 设 WW 是一个足够大的常数,使得 W>HtotalW > H_{\text{total}}。

目标函数 Z=W⋅F+HsavedZ = W \cdot F + H_{\text{saved}}。最大化 ZZ 等价于最小化成本 C=−ZC = -Z。 C=−W⋅F−HsavedC = -W \cdot F - H_{\text{saved}}.

网络构建:

  1. 节点: 源点 S=0S=0,汇点 T=2N+1T=2N+1。 VL={1,…,N}V_L = \{1, \dots, N\},VR={N+1,…,2N}V_R = \{N+1, \dots, 2N\}。
  2. 容量与费用:
    • S→iS \to i (i∈VLi \in V_L): 容量 1,费用 0。
    • N+j→TN+j \to T (N+j∈VRN+j \in V_R): 容量 1,费用 0。
    • 如果箱子 ii 包含箱子 jj,则 i→N+ji \to N+j: 容量 1,费用 ci,j=−W−Hjc_{i, j} = -W - H_j。

运行 MCMF 算法找到最大流 Fmax⁡F_{\max} 对应的最小费用 Cmin⁡C_{\min}。

2. 最优算法设计 (MCMF via Dijkstra with Potentials)

由于 N≤300N \le 300,节点数 V≤602V \le 602,边数 E≤90000E \le 90000。 HiH_i 可能高达 10910^9,因此 WW 约 3×10113 \times 10^{11},需要使用 long long 存储费用。

我们采用基于势能的 Dijkstra 算法迭代寻找增广路径:

  1. 初始化: 计算 Hi,HtotalH_i, H_{\text{total}},设定 W=Htotal+1W = H_{\text{total}} + 1。构建网络,包含大负费用边。
  2. 初始势能: 由于存在负费用边,需要先运行 SPFA 算法计算初始势能 π\pi (最短路径距离),以确保后续 Dijkstra 算法中所有边的约化费用 c′=c+πu−πvc' = c + \pi_u - \pi_v 均为非负。
  3. 迭代增广: 循环使用 Dijkstra 算法在残差网络中寻找最短路径,直到无法增广为止。每找到一条路径,更新流、残差网络和节点势能 π\pi。
  4. 结果计算: 得到 Fmax⁡F_{\max} 和 Cmin⁡C_{\min}。

Hsaved=−Cmin⁡−W⋅Fmax⁡H_{\text{saved}} = -C_{\min} - W \cdot F_{\max} Hmin⁡=Htotal−HsavedH_{\min} = H_{\text{total}} - H_{\text{saved}}

时间复杂度:O(VE+Fmax⁡Elog⁡V)O(V E + F_{\max} E \log V),对于 N=300N=300 是可接受的。

3. C++ 代码实现

C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <tuple>

using namespace std;

typedef long long ll;
const ll INF = 4e18; // Use a sufficiently large value for infinity

// Structure to hold box dimensions
struct Box {
    ll x, y, z;
    ll dims[3];
    ll height; // Min dimension
};

// Global box array
vector<Box> boxes;
int N;

// === MCMF Implementation ===
struct Edge {
    int to;
    int capacity;
    int flow;
    ll cost;
    int reverse_edge;
};

vector<vector<Edge>> adj;
vector<ll> potential;
vector<ll> dist;
vector<int> parent_node;
vector<int> parent_edge;

void add_edge(int u, int v, int cap, ll cost) {
    Edge forward = {v, cap, 0, cost, (int)adj[v].size()};
    Edge backward = {u, 0, 0, -cost, (int)adj[u].size()};
    adj[u].push_back(forward);
    adj[v].push_back(backward);
}

// Check if Box i can contain Box j based on sorted dimensions
bool can_contain(int i, int j) {
    return boxes[i].dims[0] > boxes[j].dims[0] &&
           boxes[i].dims[1] > boxes[j].dims[1] &&
           boxes[i].dims[2] > boxes[j].dims[2];
}

// Dijkstra using potentials
bool dijkstra(int s, int t, ll& total_cost, int& flow_found) {
    dist.assign(adj.size(), INF);
    parent_node.assign(adj.size(), -1);
    parent_edge.assign(adj.size(), -1);

    dist[s] = 0;

    priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;
    pq.push({0, s});

    while (!pq.empty()) {
        ll d = pq.top().first;
        int u = pq.top().second;
        pq.pop();

        if (d > dist[u]) continue;

        for (int i = 0; i < adj[u].size(); ++i) {
            Edge& e = adj[u][i];

            // Reduced cost: c' = c + pi[u] - pi[v]
            ll reduced_cost = e.cost + potential[u] - potential[e.to];

            if (e.capacity - e.flow > 0 && dist[e.to] > dist[u] + reduced_cost) {
                dist[e.to] = dist[u] + reduced_cost;
                parent_node[e.to] = u;
                parent_edge[e.to] = i;
                pq.push({dist[e.to], e.to});
            }
        }
    }

    if (dist[t] == INF) return false;

    // Update potential: pi_new(v) = pi_old(v) + d'(v)
    for (size_t i = 0; i < adj.size(); ++i) {
        if (dist[i] != INF) {
            potential[i] += dist[i];
        }
    }

    // Augment flow
    int path_flow = 1;

    // Total cost contribution: d'(T) + pi(T) - pi(S) = dist[T] + potential[T] - potential[S] (since dist[S]=0)
    // Note: potential[T] and potential[S] are already updated for the next iteration.
    // The actual cost is the reduced path cost plus potential correction: dist[T] - (potential[S] - potential[T])
    // The actual path cost is: dist[T] + potential[T] (new) - potential[S] (new)
    // Since potential[T] (new) = potential[T] (old) + dist[T] and potential[S] (new) = potential[S] (old) + dist[S] = potential[S] (old)
    // Actual cost = (dist[T] + potential[T] (old)) - potential[S] (old)

    // Simpler: total cost accumulated is based on the actual edge costs, not reduced costs.
    // The total cost accumulated in successive shortest paths is the reduced cost found by Dijkstra IF potentials are 0 initially.
    // Since we maintain potentials, the true cost of the path is:
    // Reduced Cost + potential[T] - potential[S]. (If we did not update potential yet)
    // Since we update potential right after finding distance:
    total_cost += potential[t] - potential[s];

    flow_found = path_flow;

    int curr = t;
    while (curr != s) {
        int prev = parent_node[curr];
        int edge_idx = parent_edge[curr];

        adj[prev][edge_idx].flow += path_flow;
        int rev_idx = adj[prev][edge_idx].reverse_edge;
        adj[curr][rev_idx].flow -= path_flow;
        curr = prev;
    }

    return true;
}

// SPFA for initial potential calculation
void spfa_init(int s) {
    potential.assign(adj.size(), INF);
    potential[s] = 0;
    vector<bool> in_queue(adj.size(), false);
    queue<int> q;
    q.push(s);
    in_queue[s] = true;

    while (!q.empty()) {
        int u = q.front();
        q.pop();
        in_queue[u] = false;

        for (const auto& e : adj[u]) {
            if (e.capacity - e.flow > 0) {
                if (potential[e.to] > potential[u] + e.cost) {
                    potential[e.to] = potential[u] + e.cost;
                    if (!in_queue[e.to]) {
                        q.push(e.to);
                        in_queue[e.to] = true;
                    }
                }
            }
        }
    }
    // Note: SPFA here might be slow if the graph structure is worst-case, but generally reliable for finding initial potentials.
}


pair<int, ll> min_cost_max_flow(int s, int t) {
    int max_flow = 0;
    ll min_cost = 0;

    spfa_init(s);

    int flow_increase;
    while (dijkstra(s, t, min_cost, flow_increase)) {
        max_flow += flow_increase;
    }

    return {max_flow, min_cost};
}

void solve() {
    if (!(cin >> N)) return;

    boxes.resize(N + 1);
    ll H_total = 0;

    for (int i = 1; i <= N; ++i) {
        cin >> boxes[i].x >> boxes[i].y >> boxes[i].z;
        boxes[i].dims[0] = boxes[i].x;
        boxes[i].dims[1] = boxes[i].y;
        boxes[i].dims[2] = boxes[i].z;
        sort(boxes[i].dims, boxes[i].dims + 3);

        boxes[i].height = boxes[i].dims[0];
        H_total += boxes[i].height;
    }

    if (N == 0) {
        cout << 0 << endl;
        return;
    }

    // W must be larger than H_total.
    ll W = H_total + 1;

    int S = 0;
    int T = 2 * N + 1;
    adj.assign(T + 1, vector<Edge>());

    // 1. Source to Left partition (i_L = i)
    for (int i = 1; i <= N; ++i) {
        add_edge(S, i, 1, 0);
    }

    // 2. Right partition (j_R = N + j) to Sink
    for (int j = 1; j <= N; ++j) {
        add_edge(N + j, T, 1, 0);
    }

    // 3. Nesting edges (i_L -> j_R)
    for (int i = 1; i <= N; ++i) {
        for (int j = 1; j <= N; ++j) {
            if (i == j) continue;
            if (can_contain(i, j)) {
                // Cost: -W - H_j
                ll cost = -W - boxes[j].height;
                add_edge(i, N + j, 1, cost);
            }
        }
    }

    // Run MCMF
    pair<int, ll> result = min_cost_max_flow(S, T);
    int F_max = result.first;
    ll C_min = result.second;

    // H_saved = -C_min - W * F_max
    ll H_saved = -C_min - W * (ll)F_max;
    ll H_min = H_total - H_saved;

    cout << H_min << endl;
}

int main() {
    // Fast IO
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    solve();

    return 0;
}

4. 优化与改进:贪心 + 二分图匹配

感谢 @lihugang 大佬提出的高效改进版本,该版本比原 MCMF 代码快约 15 倍。

4.1 核心思路

该版本放弃了复杂的 MCMF 建模,转而采用二分图最大匹配,并辅以两种贪心策略:

  • 贪心优化1(体积排序): 对于每个箱子,将其能放入的外层箱子按体积从小到大排序。这样优先选择“刚好能装下”的箱子,保留大箱子给更大的内层箱子。
  • 贪心优化2(高度优先): 按箱子的高度从大到小处理,优先隐藏高度大的箱子,以最大化节省的高度。

4.2 算法流程

  1. 读入并预处理所有箱子,排序三个维度,计算高度和体积。
  2. 构建邻接表,记录每个箱子能放入哪些外层箱子。
  3. 对每个箱子的邻接表按外层箱子体积排序。
  4. 将所有箱子按高度降序排序。
  5. 使用 DFS 进行二分图匹配,从高到低尝试为每个箱子寻找外层箱子。
  6. 计算被成功嵌套的箱子高度之和,输出总高度减去节省高度。

4.3 代码实现

C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

// 定义箱子结构体
struct Box {
    int id;
    int dims[3]; // 存储排序后的长宽
    int h;       // 高度(即最小的那个维度)
    long long vol; // 体积
};

// 全局变量
int n;
vector<Box> boxes;
vector<vector<int>> adj; // 邻接表
vector<int> match;       // 匹配数组 match[v] = u 表示箱子 v 装着箱子 u
vector<bool> vis;        // DFS 访问标记

// 深度优先搜索(寻找增广路)
// 尝试给箱子 u 找到一个能装下它的外层箱子 v
bool dfs(int u) {
    for (int v : adj[u]) {
        if (vis[v]) continue;
        vis[v] = true;

        // 如果箱子 v 是空的,或者箱子 v 里原本装的箱子(match[v])可以挪到别的地方
        if (match[v] == -1 || dfs(match[v])) {
            match[v] = u;
            return true;
        }
    }
    return false;
}

void solve() {
    // 1. 读取输入
    if (!(cin >> n)) return;

    boxes.resize(n);
    long long total_h = 0; // 总高度(所有箱子单独存在时)

    for (int i = 0; i < n; ++i) {
        int d1, d2, d3;
        cin >> d1 >> d2 >> d3;

        // 对应 Python: dims = sorted([d1, d2, d3])
        // 将三个维度排序,以便处理旋转
        int dims[] = {d1, d2, d3};
        sort(dims, dims + 3);

        boxes[i].id = i;
        boxes[i].dims[0] = dims[0];
        boxes[i].dims[1] = dims[1];
        boxes[i].dims[2] = dims[2];
        boxes[i].h = dims[0]; // 题目中高度贡献是最小的维度

        // 计算体积,用于后续贪心排序
        boxes[i].vol = (long long)dims[0] * dims[1] * dims[2];

        total_h += boxes[i].h;
    }

    // 2. 构建图 (邻接表)
    // 如果箱子 i 能放入箱子 j,则建立 i -> j 的边
    adj.assign(n, vector<int>());
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (i == j) continue;

            // 严格小于判定
            if (boxes[i].dims[0] < boxes[j].dims[0] &&
                boxes[i].dims[1] < boxes[j].dims[1] &&
                boxes[i].dims[2] < boxes[j].dims[2]) {
                adj[i].push_back(j);
            }
        }
    }

    // 3. 贪心优化 1:对外层箱子按体积从小到大排序
    // 对应 Python: adj[i].sort(key=lambda idx: boxes[idx]['vol'])
    // 意图:优先把当前箱子塞进能装下它的、且体积最小的箱子里(Best Fit),
    // 把大箱子留给更大的箱子用。
    for (int i = 0; i < n; ++i) {
        sort(adj[i].begin(), adj[i].end(), [](int a, int b) {
            return boxes[a].vol < boxes[b].vol;
        });
    }

    // 4. 贪心优化 2:按箱子高度从大到小处理
    // 对应 Python: sorted_indices = sorted(range(n), key=..., reverse=True)
    // 意图:优先“隐藏”高度高的箱子,能省更多高度。
    vector<int> sorted_indices(n);
    iota(sorted_indices.begin(), sorted_indices.end(), 0); // 填充 0 到 n-1
    sort(sorted_indices.begin(), sorted_indices.end(), [](int a, int b) {
        return boxes[a].h > boxes[b].h;
    });

    // 5. 二分图匹配逻辑
    match.assign(n, -1);
    long long saved_height = 0;

    for (int u : sorted_indices) {
        vis.assign(n, false); // 每次 DFS 前重置访问标记
        if (dfs(u)) {
            // 如果 u 成功被某个箱子装下,那么 u 的高度就被“省”下来了
            saved_height += boxes[u].h;
        }
    }

    // 6. 输出结果
    // 最小高度 = 所有箱子高度之和 - 成功装进去的箱子高度之和
    cout << total_h - saved_height << endl;
}

int main() {
    // 加速输入输出
    freopen("0014.in","r",stdin);
	freopen("0014.out","w",stdout);
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    solve();

    return 0;
}

5. 小结

  • MCMF 方法 更通用,建模直观,但实现复杂,常数较大。
  • 贪心 + 二分图匹配 方法利用了问题的特殊结构,通过两种贪心策略大幅提升效率,代码简洁,适合竞赛使用。

两种方法都能正确求解本题,后者在时间和代码复杂度上更具优势。

J:\bold{J:} 语文限时练习A

显然DP。

任何修改显然必然被包含在一个 TT 中。

第一位状态DP到 ii 位,第二维状态为曾将 SS 上的 i−j−m+1∼i−ji-j-m+1 \sim i-j 位改为 TT 。

预处理出 TT 与自身重叠处和 SS 与 TT 的差距,最终时空复杂度 O(NM)O(NM) 。

K:\bold{K:} 化学限时练习B

题目相当于问有多少个本质不同的有nn个节点的树,且每个节点的度数不超过4。
先考虑有i个碳的烷基数量dpidp_i,根节点上最多再连三个烷基,直接枚举其中两个烷基碳的数量x,yx,y,第三个z=i−x−yz=i-x-y,保证x≤y≤zx\le y\le z。若互不相等,则有dpx∗dpy∗dpzdp_x*dp_y*dp_z种可能,如果x=y≠z x=y \neq z则有dpz∗dpx∗(dpx+1)/2dp_z*dp_x*(dp_x+1)/2种可能。若x=y=z x=y = z则有dpx∗(dpx+1)∗(dpx+2)/3dp_x*(dp_x+1)*(dp_x+2)/3种可能。
然后找到树的重心,也是暴力枚举前三个烷基的碳的数量,保证不超过⌊n2⌋\lfloor \frac{n}{2}\rfloor,如果有相等的还是和上面一样处理,如果n为偶数,则可能有两个重心,还要去掉dpn2∗(dpn2−1)2\frac{dp_{\frac{n}{2}}*(dp_{\frac{n}{2}}-1)}{2}种情况。
关键就是要注意枚举时去重。 对于更大数据范围做法可查看luogu烷烃计数题解

AC code:

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=1e5+10,mod=998442353;
int n,dp[N],f[10][N];
int fp(int x,int y){
	if(y==0)return 1;
	int z=fp(x,y>>1);
	z=z*z%mod;
	if(y&1)return z*x%mod;
	return z;
}
int inv2,inv6,inv24;
signed main(){
	cin>>n;
	dp[0]=1;
	dp[1]=1;
	inv2=fp(2,mod-2);
	inv6=fp(6,mod-2);
	inv24=fp(24,mod-2);
	for(int p=2;p<=n/2;p++){
		int sum=0;
		for(int i=0;i<=(p-1)/3;i++){
			for(int j=i,k=(p-1)-i-j;j<=p-1&&k>=j;j++,k--){
				if(i==j&&j==k){
					sum=(sum+dp[i]*(dp[i]+1)%mod*(dp[i]+2)%mod*inv6%mod)%mod;
				}else if(i==j){
					sum=(sum+(dp[j]*(dp[j]+1)%mod*inv2%mod)*dp[k]%mod)%mod;
				}else if(j==k){
					sum=(sum+(dp[j]*(dp[j]+1)%mod*inv2%mod)*dp[i]%mod)%mod;
				}else{
					sum=(sum+dp[i]*dp[j]%mod*dp[k]%mod)%mod;
				}
			}
		}
		dp[p]=sum;
	}
	int p=n;
	int hf=p/2,ans=0;
	for(int i=0;i<=hf;i++){
		for(int j=i;j<=hf;j++){
			for(int k=max(j,p-1-i-j-hf),l=p-1-i-j-k;k<=hf&&l>=k;k++,l--){
				if(i==j&&j==k&&k==l){
					ans+=dp[i]*(dp[i]+1)%mod*(dp[i]+2)%mod*(dp[i]+3)%mod*inv24%mod;
					ans%=mod;
				}else if(i==j&&j==k){
					ans+=dp[l]*dp[i]%mod*(dp[i]+1)%mod*(dp[i]+2)%mod*inv6%mod;
					ans%=mod;
				}else if(j==k&&k==l){
					ans+=dp[i]*dp[k]%mod*(dp[k]+1)%mod*(dp[k]+2)%mod*inv6%mod;
					ans%=mod;
				}else if(i==j&&k==l){
					ans+=dp[i]*(dp[i]+1)%mod*inv2%mod*dp[k]%mod*(dp[k]+1)%mod*inv2%mod;
					ans%=mod;
				}else if(i==j){
					ans+=dp[i]*(dp[i]+1)%mod*inv2%mod*dp[k]%mod*dp[l]%mod;
					ans%=mod;
				}else if(j==k){
					ans+=dp[j]*(dp[j]+1)%mod*inv2%mod*dp[i]%mod*dp[l]%mod;
					ans%=mod;
				}else if(k==l){
					ans+=dp[k]*(dp[k]+1)%mod*inv2%mod*dp[i]%mod*dp[j]%mod;
					ans%=mod;
				}else{
					ans+=dp[i]*dp[j]%mod*dp[k]%mod*dp[l]%mod;
					ans%=mod;
				}
			}
		}
	}
	if(p%2==0){
		ans=(ans+mod-dp[hf]*(dp[hf]-1)%mod*inv2%mod)%mod;
	}
	cout<<ans<<endl;
	return 0;
}
原文