题解:P17130 [ICPC 2025 Shanghai R] Yet another mailbox problem
题目简述
给定一个有向图,边权 -1。
思路
路径的字典序只由权重序列决定。直接把所有权重序列看成一棵字典树:根是空串,每个节点往下连
我们对字典树按
对每个权重序列,只记录它对应的所有路径终点(多重集)dfs(x, S),其中
其中每条边贡献一次,所以
处理
- 先输出
|S'| 条长度为x+1 的路径; - 若
S'\neq\varnothing ,直接递归dfs(x+1, S')。
::::info[证明]
设当前的前缀为
因为第一处不同在位置
又
::::
代码
无需解释,模拟即可。
#include<bits/stdc++.h>
using namespace std;
int n,m,k;
vector<int> e[500005][9];
struct F {
int x,w;
vector<int>y;
};
int main() {
cin>>n>>m>>k;
for(int i=1; i<=m; i++) {
int x,y,z;
cin>>x>>y>>z;
e[x][z].push_back(y);
}
vector<int>s(n);
iota(s.begin(),s.end(),1);
vector<F> st;
st.push_back({0,1,s});
while(!st.empty()) {
F&f=st.back();
if(f.w>8) {
st.pop_back();
continue;
}
int w=f.w++;
vector<int>p;
for(int u:f.y){
for(int v:e[u][w]) {
cout<<f.x+1<<"\n";
if(--k==0) return 0;
p.push_back(v);
}
}
if(!p.empty()) st.push_back({f.x+1,1,move(p)});
}
while(k--) cout<<"-1\n";
}