2022 暑期高一生集训资料 Part 1

· · 个人记录

本文有知识性错误待修改(按秩合并少一行代码)

日程安排

资源使用指南

通用参考资料

第一部分 图论 Graph Theory

图论在信息学竞赛中是一个很大的考点,据不完全统计,其包含的知识点数量有八十余个。在所有的图论知识中,我们本次集训的内容是较为基础的部分,其中有些内容和 CSP-J/S 第一轮直接相关,有些内容无论是从最简单的比赛还是到最盛大的赛事都会考察到。学习本部分图论内容,能够明白原理自己推导为合格,熟练打出代码并且不出错为优秀。不过,我校的图论水平相对较高(指的是比其他考点讲得更加细致全面),因此不必担心图论学不好。

Day 1

参考资料
例题链接
标准程序

查找文献 使用 std::set 排序后做 DFS 与 BFS O(|V|\log |V|)

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <set>
#include <queue>
const int sz=1e6+19;
int n,m;
std::set<int> graph[sz];
unsigned char vis[sz];
void DFS(int u){
  if(vis[u]) return;
  vis[u]=1,std::cout<<u<<' ';
  for(auto cx:graph[u]) DFS(cx);
}
std::queue<int> qq;
void BFS(int u){
  qq.push(u);
  while(!qq.empty()){
    int u=qq.front();
    qq.pop();
    if(vis[u]) continue;
    vis[u]=1;
    std::cout<<u<<' ';
    for(auto cx:graph[u]) qq.push(cx);
  }
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n>>m;
  for(int cx=1,u,v;cx<=m;++cx){
    std::cin>>u>>v;
    graph[u].insert(v);
  }
  DFS(1);
  std::cout<<'\n';
  std::fill(vis,vis+n+1,0);
  BFS(1);
  return 0;
}

信息传递 直接 DFS 找环 O(|V|)

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <limits>
const int inf=std::numeric_limits<int>::max();
const int sz=2e5+19;
int n,ps[sz],sid[sz],ans=inf/2;
unsigned char vis[sz];
void DFS(int u,int step){
  if(vis[u]) return;
  if(sid[u]) return ans=std::min(ans,step-sid[u]),void();
  sid[u]=step,DFS(ps[u],step+1),vis[u]=1;
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n;
  for(int cx=1;cx<=n;++cx) std::cin>>ps[cx];
  for(int cx=1;cx<=n;++cx) if(!vis[cx]) DFS(cx,0);
  std::cout<<ans<<std::endl;
  return 0;
}

传递闭包 插点思想 O(|V|^3)

#include <iostream>
#include <bitset>
const int sz=102;
int n,graph[sz][sz];
int main(){
  std::cin>>n;
  for(int cx=1,u;cx<=n;++cx){
    for(int cy=1;cy<=n;++cy){
      std::cin>>u;
      if(u==1) graph[cx][cy]=1;
    }
  }
  for(int p=1;p<=n;++p)
    for(int cx=1;cx<=n;++cx)
      for(int cy=1;cy<=n;++cy)
        graph[cx][cy]=graph[cx][cy]|(graph[cx][p]&graph[p][cy]);
  for(int cx=1;cx<=n;++cx){
    for(int cy=1;cy<=n;++cy)
      std::cout<<graph[cx][cy]<<' ';
    std::cout<<std::endl;
  }
  return 0;
}

std::bitset 优化传递闭包 O(\frac {|V|^3}{w})

#include <iostream>
#include <algorithm>
#include <bitset>
const int sz=102;
int n;
std::bitset<sz> graph[sz];
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.tie(nullptr)->sync_with_stdio(false);
  std::cin>>n;
  for(int cx=1,u;cx<=n;++cx){
    for(int cy=1;cy<=n;++cy){
      std::cin>>u;
      if(u==1) graph[cx].set(cy);
    }
  }
  for(int cy=1;cy<=n;++cy)
    for(int cx=1;cx<=n;++cx)
      if(graph[cx].test(cy)) graph[cx]|=graph[cy];
  for(int cx=1;cx<=n;++cx){
    for(int cy=1;cy<=n;++cy)
      std::cout<<(graph[cx].test(cy)?1:0)<<' ';
    std::cout<<std::endl;
  }
  return 0;
}

单源最短路径(弱化版) 使用 SPFA O(|V||E|)。

#include <iostream>
#include <algorithm>
#include <queue>
#include <limits>
using ll=long long;
const ll inf=std::numeric_limits<int>::max();
const int sz=1e4+19;
const int esz=5e5+19;
int n,m,s,head[sz],hpp=0;
struct edge{
  int nxt,to,w;
}graph[esz];
void addEdge(int from,int to,int w){
  graph[++hpp]=edge{head[from],to,w};
  head[from]=hpp;
}
ll dist[sz];
unsigned char inQueue[sz];
void SPFA(int s){
  std::queue<int> qq;
  std::fill(dist,dist+n+1,inf);
  std::fill(inQueue,inQueue+n+1,0);
  dist[s]=0,qq.push(s),inQueue[s]=1;
  while(!qq.empty()){
    int u=qq.front();
    qq.pop(),inQueue[u]=0;
    for(int p=head[u];p!=0;p=graph[p].nxt){
      int v=graph[p].to;
      if(dist[u]+graph[p].w<dist[v]){
        dist[v]=dist[u]+graph[p].w;
        if(!inQueue[v]) qq.push(v),inQueue[v]=1;
      }
    }
  }
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n>>m>>s;
  for(int cx=1,u,v,w;cx<=m;++cx){
    std::cin>>u>>v>>w;
    addEdge(u,v,w);
  }
  SPFA(s);
  for(int cx=1;cx<=n;++cx)
    std::cout<<dist[cx]<<' ';
  return 0;
}

单源最短路径(标准版) 使用 Dijkstra O(|E|\log|V|)

#include <iostream>
#include <functional>
#include <algorithm>
#include <queue>
#include <vector>
#include <limits>
using ll=long long;
using plit=std::pair<ll,int>;
const ll inf=std::numeric_limits<ll>::max()/2;
const int sz=1e5+19;
const int esz=2e5+19;
int n,m,s,head[sz],hpp;
struct edge{
  int nxt,to,w;
}graph[esz];
void addEdge(int from,int to,int w){
  graph[++hpp]=edge{head[from],to,w};
  head[from]=hpp;
}
ll dist[sz];
unsigned char vis[sz];
void Dijkstra(int s){
  std::priority_queue<plit,std::vector<plit>,std::greater<plit>> pq;
  std::fill(dist,dist+n+1,inf);
  std::fill(vis,vis+n+1,0);
  dist[s]=0,pq.push(std::make_pair(0,s));
  while(!pq.empty()){
    int u=pq.top().second;
    pq.pop();
    if(vis[u]) continue;
    vis[u]=1;
    for(int p=head[u];p!=0;p=graph[p].nxt){
      int v=graph[p].to;
      if(dist[u]+graph[p].w<dist[v])
        dist[v]=dist[u]+graph[p].w,pq.push(std::make_pair(dist[v],v));
    }
  }
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n>>m>>s;
  for(int cx=1,u,v,w;cx<=m;++cx){
    std::cin>>u>>v>>w;
    addEdge(u,v,w);
  }
  Dijkstra(s);
  for(int cx=1;cx<=n;++cx)
    std::cout<<dist[cx]<<' ';
  return 0;
}

负环 使用 SPFA O(|V||E|),注意本题只问了有没有 1 能到的负环,1 不能到的负环没有问,所以不用建超级源点,一切照常。

#include <iostream>
#include <algorithm>
#include <queue>
#include <limits>
using ll=long long;
const ll inf=std::numeric_limits<ll>::max()/2;
const int sz=2e3+19;
const int esz=6e3+19;
int T,n,m,head[sz],hpp=0;
struct edge{
  int nxt,to,w;
}graph[esz];
void addEdge(int from,int to,int w){
  graph[++hpp]=edge{head[from],to,w};
  head[from]=hpp;
}
int pathLength[sz];
ll dist[sz];
unsigned char inQueue[sz];
bool SPFA(int s){
  std::queue<int> qq;
  std::fill(dist,dist+n+1,inf);
  std::fill(inQueue,inQueue+n+1,0);
  std::fill(pathLength,pathLength+n+1,1);
  dist[s]=0,qq.push(s),inQueue[s]=1;
  while(!qq.empty()){
    int u=qq.front();
    qq.pop(),inQueue[u]=0;
    if(pathLength[u]>n) return false;
    for(int p=head[u];p!=0;p=graph[p].nxt){
      int v=graph[p].to;
      if(dist[u]+graph[p].w<dist[v]){
        dist[v]=dist[u]+graph[p].w,pathLength[v]=pathLength[u]+1;
        if(!inQueue[v]) qq.push(v),inQueue[v]=1;
      }
    }
  }
  return true;
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>T;
  while(T--){
    std::fill(graph,graph+hpp+1,edge{0,0,0});
    std::fill(head,head+n+1,0);
    hpp=0;
    std::cin>>n>>m;
    for(int cx=1,u,v,w;cx<=m;++cx){
      std::cin>>u>>v>>w;
      if(w>=0) addEdge(u,v,w),addEdge(v,u,w);
      else addEdge(u,v,w);
    }
    std::cout<<(SPFA(1)?"NO":"YES")<<std::endl;
  }
  return 0;
}

全源最短路径 使用 Johnson O(|V||E|\log |E|),注意我们为了判断全图上是否有负环加入了超级源点,因此 |V|=n+1,判断负环时注意条件。如果不慎写成 if(pathLength>n) 会被链状的图给卡掉。

#include <iostream>
#include <functional>
#include <algorithm>
#include <queue>
using ll=long long;
using plit=std::pair<ll,int>;
const ll inf=1e9;
const int sz=3e3+19;
const int esz=9e3+19;
int n,m,head[sz],hpp=0;
struct edge{
  int nxt,to,w;
}graph[esz];
void addEdge(int from,int to,int w){
  graph[++hpp]=edge{head[from],to,w};
  head[from]=hpp;
}
int pathLength[sz];
ll h[sz];
unsigned char inQueue[sz];
bool SPFA(int s){
  std::queue<int> qq;
  std::fill(h,h+n+1,inf);
  std::fill(inQueue,inQueue+n+1,0);
  std::fill(pathLength,pathLength+n+1,1);
  h[s]=0,qq.push(s),inQueue[s]=1;
  while(!qq.empty()){
    int u=qq.front();
    qq.pop(),inQueue[u]=0;
    if(pathLength[u]>n+1) return false;
    for(int p=head[u];p!=0;p=graph[p].nxt){
      int v=graph[p].to;
      if(h[u]+graph[p].w<h[v]){
        h[v]=h[u]+graph[p].w,pathLength[v]=pathLength[u]+1;
        if(!inQueue[v]) qq.push(v),inQueue[v]=1;
      }
    }
  }
  return true;
}
ll dist[sz];
unsigned char vis[sz];
void Dijkstra(int s){
  std::priority_queue<plit,std::vector<plit>,std::greater<plit>> pq;
  std::fill(dist,dist+n+1,inf);
  std::fill(vis,vis+n+1,0);
  dist[s]=0,pq.push(std::make_pair(0,s));
  while(!pq.empty()){
    int u=pq.top().second;
    pq.pop();
    if(vis[u]) continue;
    vis[u]=1;
    for(int p=head[u];p!=0;p=graph[p].nxt){
      int v=graph[p].to;
      if(dist[u]+graph[p].w<dist[v])
        dist[v]=dist[u]+graph[p].w,pq.push(std::make_pair(dist[v],v));
    }
  }
}
void Johnson(){
  for(int cx=1;cx<=n;++cx){
    Dijkstra(cx);
    ll ans=0;
    for(int cy=1;cy<=n;++cy){
      if(dist[cy]>=inf) ans+=1LL*cy*inf;
      else ans+=1LL*cy*(dist[cy]-h[cx]+h[cy]);
    }
    std::cout<<ans<<std::endl;
  }
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n>>m;
  for(int cx=0,u,v,w;cx<m;++cx){
    std::cin>>u>>v>>w;
    addEdge(u,v,w);
  }
  for(int cx=1;cx<=n;++cx)
    addEdge(0,cx,0);
  if(!SPFA(0)) std::cout<<-1<<std::endl;
  else{
    for(int cx=1;cx<=n;++cx){
      for(int p=head[cx];p!=0;p=graph[p].nxt)
        graph[p].w+=h[cx]-h[graph[p].to];
    }
    Johnson();
  }
  return 0;
}

路径统计 使用 SPFA O(|V||E|),注意使用 SPFA 时只有最后一轮跑的才是正确的,因此效率很低(换言之可以被卡),有关最短路计数这一类的问题,我曾经和 Mine_King 讨论过,并由 ta 给了若干 hack 数据,以前很多题解都是错的,想要更好地理解最短路计数类问题戳:# 关于用 spfa 做路径统计的一点问题 及 # 请求撤下所有直接 SPFA 做最短路计数的题解或仅保留一篇。我也曾经写过一个 Dijkstra 的版本,不过这里不放了,鼓励大家自己思考完成这道题目。

#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <queue>
#include <limits>
using ll=long long;
using piit=std::pair<int,int>;
const ll inf=std::numeric_limits<ll>::max()/2;
const int sz=2022;
const int esz=4e6+19;
namespace std{
  template<>struct hash<piit>{
    size_t operator()(const piit &x)const{
      return hash<ll>()(1LL*x.first<<32|x.second);
    }
  };
}
int n,m,head[sz],hpp=0;
std::unordered_map<piit,int> em;
struct edge{
  int nxt,to,w;
}graph[esz];
void addEdge(int from,int to,int w){
  graph[++hpp]=edge{head[from],to,w};
  head[from]=hpp;
}
ll ans[sz],dist[sz];
unsigned char inQueue[sz];
void SPFA(int s){
  std::fill(dist,dist+n+1,inf);
  std::fill(inQueue,inQueue+n+1,0);
  std::queue<int> qq;
  qq.push(s),dist[s]=0,ans[s]=1,inQueue[s]=true;
  while(!qq.empty()){
    int u=qq.front();
    qq.pop(),inQueue[u]=0;
    if(u==n) continue;
    for(int cx=head[u];cx!=0;cx=graph[cx].nxt){
      int v=graph[cx].to;
      if(dist[v]==dist[u]+graph[cx].w)
        ans[v]+=ans[u];
      if(dist[v]>dist[u]+graph[cx].w)
        ans[v]=ans[u],dist[v]=dist[u]+graph[cx].w;
      if(ans[v]&&!inQueue[v])
        qq.push(v),inQueue[v]=1;
    }
    ans[u]=0;
  }
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n>>m;
  for(int cx=0,u,v,w;cx<m;++cx){
    std::cin>>u>>v>>w;
    piit cur=std::make_pair(u,v);
    if(em[cur]==0) em[cur]=(1<<28);
    em[cur]=std::min(em[cur],w);
  }
  for(auto it=em.begin();it!=em.end();++it){
    int u=it->first.first,v=it->first.second,w=it->second;
    addEdge(u,v,w);
  }
  SPFA(1);
  if(dist[n]>=inf) std::cout<<"No answer"<<std::endl;
  else std::cout<<dist[n]<<' '<<ans[n]<<std::endl;
  return 0;
}

通往奥格瑞玛的道路 使用二分答案,判定时使用最短路算法,可以做到O(|E|\log |V|\log \underset{i\in E}{\max} f_i),代码略。

冻结 使用分层建图的思想,每层都和原图相同,而在相邻两层中间,若上一层有边 (u,v),则可在本层的 u 和下一层与 v 对应的 v^\prime 连一条有向边,权值为 0,代表原图上 (u,v) 免费的情况,建 (k+1) 层图即可,可以做到 O(k|E|(\log|V|+\log k)),代码略。

Day 2

参考资料
例题链接

如果觉得上午的题太简单的话就对了,想必昨天最短路的练习有点多吧,那就今天上午 \overset{\mathtt{upsolve}}{补一补题} 吧。

标准程序

求先序排列 后序遍历的最后一位是当前的根,中序遍历中根的左右分别是左右子树,使用 DFS 可以做到 O(|V|^2)。如果你质疑 DFS 的复杂度的话,可以用主定理求时间复杂度。为了简化符号,我们记 n 为字符串长度,则有:

T(n)=T(n-x)+T(x),T(1)=1

注意到每层的 x 和 n 的取值都不一定相同,但是每层都是 O(n) 的(由上式 x=1 时叠加求得),因此只需要看 DFS 层数多少即可,当 \forall x=1 的时候(此时树是一条链,DFS O(n) 层)T(n)=O(n)+O(n-1)+O(1)+O(n-2)+2O(1)+O(n-3)+3O(1)+\cdots=O(n^2) 取最大值,当 \forall x=\frac n 2 的时候(此时树是满二叉树,DFS O(\log n) 层)T(n)=O(n)+2O(\frac n 2)+4O(\frac n 4)+\cdots=O(n\log n) 取最小值,证毕。

#include <iostream>
#include <string>
std::string midTrav,postTrav;
void DFS(int mln,int mrn,int pln,int prn){
  if(mln>mrn||pln>prn) return;
  char ch=postTrav[prn];
  int chpos=0;
  std::cout<<ch;
  for(int cx=mln;cx<=mrn;++cx)
    if(midTrav[cx]==ch) chpos=cx;
  DFS(mln,chpos-1,pln,pln-mln+chpos-1);
  DFS(chpos+1,mrn,prn-mrn+chpos,prn-1);
}
int main(){
  std::cin>>midTrav>>postTrav;
  int n=midTrav.length();
  DFS(0,n-1,0,n-1);
  return 0;
}

对称二叉树 使用记录左右儿子的方法存储这个二叉树比较方便,暴力枚举节点,看看当前节点所代表的子树是不是对称的,然后更新答案,可以预处理出子树大小,然后 DFS 判定子树是否对称,可以做到 O(|V|^2),只给判定子树对称的函数代码,完整代码略。

bool checkPalindrome(int lson,int rson){
  if(lson==-1&&rson==-1) return true;
  if(lson==-1||rson==-1) return false;
  if(weight[lson]!=weight[rson]) return false;
  return checkPalindrome(ch[lson][0],ch[rson][1])&&
         checkPalindrome(ch[lson][1],ch[rson][0]);
}

巡逻 k=1 时直接把直径连起来即可,易证其正确性,k=2 时求出树的直径之后可以考虑加上第二条边之后产生的第二个环的情况,要么它和前一个环有重叠,要么它和前一个环没有重叠。对于后者显然贪心,把忽略掉前一个环的部分的直径连起来即可。而对于前者,造出来的那条边只能经过一次,因此第二次产生的环和前一次产生的环的公共边的距离并没有节省,考虑把这部分补出来,在第二次求直径的时候我们做一个 DP,路过一条边的时候如果这个边的两端点都在前一个环上的时候就把这条边的权值设为 -1,其余部分正常 DP 不变即可。时间复杂度 O(|V|)。本题有我的视频讲解,# 信息学竞赛半月刊-2 月 B 刊 跳转到 01:19 就是了。

#include <iostream>
#include <algorithm>
#include <cstdlib>
const int sz=1e5+19;
const int esz=2e5+19;
int n,k,head[sz],hpp=0;
struct edge{
  int nxt,to,w;
}graph[esz];
void addEdge(int from,int to,int w){
  graph[++hpp]=edge{head[from],to,w};
  head[from]=hpp;
}
int root,dist[sz],fa[sz],L1;
char inDiameter[sz];
void DFS(int u,int fau){
  fa[u]=fau;
  if(dist[u]>dist[root]) root=u;
  for(int p=head[u];p!=0;p=graph[p].nxt){
    int v=graph[p].to;
    if(v==fau) continue;
    dist[v]=dist[u]+graph[p].w;
    DFS(v,u);
  }
}
int L2,mxd[sz],mx2d[sz];
void DP(int u,int fau){
  mxd[u]=0,mx2d[u]=0;
  for(int p=head[u];p!=0;p=graph[p].nxt){
    int v=graph[p].to;
    if(v==fau) continue;
    if(inDiameter[u]&&inDiameter[v]) graph[p].w=-1;
    DP(v,u);
    int x=mxd[v]+graph[p].w;
    if(x>mxd[u]) mx2d[u]=mxd[u],mxd[u]=x;
    else if(x>mx2d[u]) mx2d[u]=x;
  }
  L2=std::max(L2,mxd[u]+mx2d[u]);
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n>>k;
  for(int cx=1,u,v;cx<n;++cx){
    std::cin>>u>>v;
    addEdge(u,v,1),addEdge(v,u,1);
  }
  root=1,DFS(root,0);
  dist[root]=0,DFS(root,0);
  L1=dist[root];
  if(k==1) std::cout<<((n<<1)-1-L1)<<std::endl;
  else{
    for(int cx=root;cx!=0;cx=fa[cx])
      inDiameter[cx]=1;
    DP(1,0);
    std::cout<<((n<<1)-L1-L2)<<std::endl;
  }
  return 0;
}

消防 欲使最大值最小,考虑二分,判断时先判断树的直径上的点,看看距离直径一端距离小于二分的值 x 的离端点最远的两点,看看他们距离是不是超过了 s,再判断其他点到直径上的点的距离的最值是否小于等于你二分的值 x。这样做的话,时间复杂度是 O(|V|\log \underset{i\in E}{\sum}w_i) ,这里我二分的边界没有卡得很准,所以略微增大了常数。

#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <limits>
using piit=std::pair<int,int>;
const int inf=std::numeric_limits<int>::max()/2;
const int sz=3e5+19;
const int esz=6e5+33;
int n,k,head[sz],hpp=0;
struct edge{
  int nxt,to,w;
}graph[esz];
void addEdge(int from,int to,int w){
  graph[++hpp]=edge{head[from],to,w};
  head[from]=hpp;
}
int root,dist[sz],fa[sz];
unsigned char vis[sz];
std::vector<piit> ptv;
void DFS(int u,int fau){
  fa[u]=fau;
  if(dist[u]>dist[root]) root=u;
  for(int p=head[u],v;p!=0;p=graph[p].nxt){
    v=graph[p].to;
    if(v==fau||vis[v]) continue;
    dist[v]=dist[u]+graph[p].w;
    DFS(v,u);
  }
}
int BFS(int s){
  std::queue<int> qq;
  int res=0;
  qq.push(s);
  while(!qq.empty()){
    int u=qq.front();
    qq.pop(),res=std::max(res,dist[u]);
    for(int p=head[u];p!=0;p=graph[p].nxt){
      int v=graph[p].to;
      if(vis[v]) continue;
      vis[v]=true;
      dist[v]=dist[u]+graph[p].w;
      qq.push(v);
    }
  }
  return res;
}
bool check(int x){
  std::fill(vis,vis+n+1,0);
  std::fill(dist,dist+n+1,0);
  int pu=0,pv=int(ptv.size())-1;
  while(pu+1<ptv.size()&&ptv[pu+1].second<=x) pu++;
  while(pv!=0&&ptv.rbegin()->second-ptv[pv-1].second<=x) pv--;
  if(pu>pv) return true;
  if(ptv[pv].second-ptv[pu].second>k) return false;
  for(auto cx:ptv) vis[cx.first]=1;
  for(int cx=pu;cx<=pv;++cx)
    if(BFS(ptv[cx].first)>x) return false;
  return true;
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n>>k;
  for(int cx=1,u,v,w;cx<n;++cx){
    std::cin>>u>>v>>w;
    addEdge(u,v,w),addEdge(v,u,w);
  }
  root=1,DFS(root,0);
  dist[root]=0,DFS(root,0);
  for(int cx=root;cx!=0;cx=fa[cx])
    ptv.push_back(std::make_pair(cx,dist[cx]));
  std::reverse(ptv.begin(),ptv.end());
  int ln=0,rn=inf;
  while(ln<rn-1){
    int mid=(ln+rn)>>1;
    if(check(mid)) rn=mid;
    else ln=mid;
  }
  std::cout<<rn<<std::endl;
  return 0;
}

Tree Destruction 在一棵边权均为 1 的树上,可以用反证法证明,距离树上某点最远的点为树的直径的某端点,把树的直径求出来并记录两个端点,然后 DFS 判断不在直径上的点离哪个端点远,把它们删掉,再删去直径上的点即可。这样做,时间复杂度为 O(|V|)。

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <limits>
using piit=std::pair<int,int>;
using ll=long long;
const int sz=2e5+19;
const int esz=4e5+19;
int n,head[sz],hpp=0;
struct edge{
  int nxt,to;
}graph[esz];
void addEdge(int from,int to){
  graph[++hpp]=edge{head[from],to};
  head[from]=hpp;
}
int root,du,dv,dist[sz],fa[sz];
unsigned char vis[sz];
std::vector<piit> ansv;
void DFS(int u,int fau){
  fa[u]=fau;
  if(dist[u]>dist[root]) root=u;
  for(int p=head[u];p!=0;p=graph[p].nxt){
    int v=graph[p].to;
    if(v==fau||vis[v]) continue;
    dist[v]=dist[u]+1;
    DFS(v,u);
  }
}
ll ans;
void finalDFS(int u,int rt){
  for(int p=head[u];p!=0;p=graph[p].nxt){
    int v=graph[p].to;
    if(dist[v]>dist[u]) finalDFS(v,vis[v]?v:rt);
  }
  if(!vis[u]){
    if(dist[u]>dist[u]+dist[dv]-2*dist[rt])
      ans+=dist[u],ansv.push_back(std::make_pair(du,u));
    else ans+=dist[u]+dist[dv]-2*dist[rt],ansv.push_back(std::make_pair(dv,u));
  }
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n;
  for(int cx=1,u,v;cx<n;++cx){
    std::cin>>u>>v;
    addEdge(u,v),addEdge(v,u);
  }
  root=1,DFS(root,0),du=root;
  dist[root]=0,DFS(root,0),dv=root;
  for(int cx=root;cx!=0;cx=fa[cx]) vis[cx]=1;

  finalDFS(du,du);
  for(int cx=dv;cx!=du;cx=fa[cx])
    ans+=dist[cx],ansv.push_back(std::make_pair(du,cx));
  std::cout<<ans<<std::endl;
  for(auto cx:ansv)
    std::cout<<cx.first<<' '<<cx.second<<' '<<cx.second<<'\n';
  return 0;
}

Day 3

参考资料
例题链接
标准程序

ST 表 这里只给核心代码,O(n \log n)。

初始化部分:

for(int w=1;w<=std::__lg(n);++w){
  for(int cx=1;cx+(1<<w)-1<=n;++cx)
    f[w][cx]=std::min(f[w-1][cx],f[w-1][cx+(1<<(w-1))]);
}

查询部分:

int w=std::lg(rn-ln+1);
std::cout<<std::max(f[w][ln],f[w][rn-(1<<w)+1])<<'\n';

最近公共祖先 使用 DFS 序和 DFN 求 LCA,时间复杂度 O(|V|\log |V|+q)。

#include <iostream>
#include <algorithm>
const int sz=5e5+19;
const int esz=1e6+39;
const int logsz=19;
int n,m,root,head[sz],hpp=0;
struct edge{
  int nxt,to;
}graph[esz];
void addEdge(int from,int to){
  graph[++hpp]=edge{head[from],to};
  head[from]=hpp;
}
int dpp,dfn[sz],dep[sz],f[logsz][sz];
void DFS(int u,int fau){
  ++dpp,dfn[u]=dpp,f[0][dpp]=fau,dep[u]=dep[fau]+1;
  for(int p=head[u];p!=0;p=graph[p].nxt)
    if(graph[p].to!=fau) DFS(graph[p].to,u);
}
inline int depmin(int u,int v){
  return (dep[u]<dep[v])?u:v;
}
int LCA(int u,int v){
  if(u==v) return u;
  int du=dfn[u],dv=dfn[v];
  if(du>dv) std::swap(du,dv);
  int w=std::__lg(dv-du);
  return depmin(f[w][du+1],f[w][dv-(1<<w)+1]);
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n>>m>>root;
  for(int cx=1,u,v;cx<n;++cx){
    std::cin>>u>>v;
    addEdge(u,v),addEdge(v,u);
  }
  DFS(root,0);
  for(int w=1;w<=std::__lg(n);++w){
    for(int cx=1;cx+(1<<w)-1<=n;++cx)
      f[w][cx]=depmin(f[w-1][cx],f[w-1][cx+(1<<(w-1))]);
  }
  for(int cx=1,u,v;cx<=m;++cx){
    std::cin>>u>>v;
    std::cout<<LCA(u,v)<<'\n';
  }
  return 0;
}

紧急集合 其实就是要找到一个点,使给定的树上三个点和这个点距离之和最小,我们可以手画一下图,进行分类讨论,发现如果三个点的 LCA 不全相同,只要找到三个点的 LCA 中不公共的那个就可以了;而如果三个点的 LCA 相同则直接选那个 LCA 即可。(猜测的这个结论可以证明)这样做本题,时间复杂度 O(|V|\log |V|+q)。

#include <iostream>
#include <algorithm>
const int sz=5e5+19;
const int esz=1e6+19;
const int logsz=std::__lg(sz)+1;
int n,m,head[sz],hpp=0;
struct edge{
  int nxt,to;
}graph[esz];
void addEdge(int from,int to){
  graph[++hpp]=edge{head[from],to};
  head[from]=hpp;
}
int dpp,dfn[sz],dep[sz],f[logsz][sz];
void DFS(int u,int fau){
  ++dpp,dfn[u]=dpp,f[0][dpp]=fau,dep[u]=dep[fau]+1;
  for(int p=head[u];p!=0;p=graph[p].nxt)
    if(graph[p].to!=fau) DFS(graph[p].to,u);
}
inline int depmin(int u,int v){
  return (dep[u]<dep[v])?u:v;
}
int LCA(int u,int v){
  if(u==v) return u;
  int du=dfn[u],dv=dfn[v];
  if(du>dv) std::swap(du,dv);
  int w=std::__lg(dv-du);
  return depmin(f[w][du+1],f[w][dv-(1<<w)+1]);
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n>>m;
  for(int cx=1,u,v;cx<n;++cx){
    std::cin>>u>>v;
    addEdge(u,v),addEdge(v,u);
  }
  DFS(1,0);
  for(int w=1;w<=std::__lg(n);++w){
    for(int cx=1;cx+(1<<w)-1<=n;++cx)
      f[w][cx]=depmin(f[w-1][cx],f[w-1][cx+(1<<(w-1))]);
  }
  while(m--){
    int x,y,z;
    std::cin>>x>>y>>z;
    int l1=LCA(x,y),l2=LCA(y,z),l3=LCA(z,x),tg,ans;
    if(l1==l2) tg=l3;
    if(l2==l3) tg=l1;
    if(l3==l1) tg=l2;
    ans=dep[x]+dep[y]+dep[z]-dep[l1]-dep[l2]-dep[l3];
    std::cout<<tg<<' '<<ans<<'\n';
  }
  return 0;
}

Max Flow P 和 松鼠的新家 都是树上差分典型题,使用点差分即可,比较简单直白。

运输计划 是树上差分和二分结合的一道题目,二分最短时间,判断时使用边差分,虫洞相当于是将某条边删去来减少路径的耗时,假设如果有若干条路径的时间大于你二分的这个最短时间,那么就需要将这些路径上的公共边用虫洞连起来,这样的话这些路径时间就都比你二分的那个最短时间小了,如果存在这么一条边,那么你二分的这个值就是合法的。时间复杂度 O(|V|\log \underset{(i,j)\in \mathtt{Plans}}{\max}L_{\delta(i,j)})。

天天爱跑步 是一道综合性比较强的题目,也很符合信息学竞赛高等级题目的特点:思维量和代码量较大。在做这道题时你可能会被它的描述给带歪了:解决问题并不主要在于玩家跑到了哪里,关键在观察者上。也就是说,这道题的研究对象其实是观察员,看看有多少个玩家对他的观察产生了贡献,进行分类讨论并加上大量的推理,推知能对某个点 u 做贡献的起点或终点一定都在以 u 为根的子树上。问题转化为求子树贡献,继续转化问题,可以转化到树上差分和桶上去。完整思路很长,这里限于篇幅不再多说,下面放一个我写的时间复杂度 O(|V|\log |V|) 的代码。

#include <iostream>
#include <algorithm>
#include <cstdlib>
const int sz=3e5+19;
const int esz=6e5+39;
const int logsz=19;
int n,m;
struct graph{
  int head[sz],hpp=0;
  struct edge{
    int nxt,to;
  }graph[esz];
  void addEdge(int from,int to){
    graph[++hpp]=edge{head[from],to};
    head[from]=hpp;
  }
}g0,g1,g2;
int dpp,dfn[sz],dep[sz],f[logsz][sz],dist[sz];
inline int depmin(int u,int v){
  return (dep[u]<dep[v])?u:v;
}
inline int LCA(int u,int v){
  if(u==v) return u;
  int du=dfn[u],dv=dfn[v];
  if(du>dv) std::swap(du,dv);
  int w=std::__lg(dv-du);
  return depmin(f[w][du+1],f[w][dv-(1<<w)+1]);
}
void LCADFS(int u,int fau){
  ++dpp,dfn[u]=dpp,dep[u]=dep[fau]+1,f[0][dpp]=fau;
  for(int p=g0.head[u];p!=0;p=g0.graph[p].nxt){
    int v=g0.graph[p].to;
    if(v==fau) continue;
    LCADFS(v,u);
  }
}
int w[sz],s[sz],t[sz],scnt[sz],ans[sz];
int buc1[sz<<1],buc2[sz<<1];
void DFS(int u,int fau){
  int w1=buc1[w[u]+dep[u]],w2=buc2[w[u]-dep[u]+sz];
  for(int p=g0.head[u];p!=0;p=g0.graph[p].nxt){
    int v=g0.graph[p].to;
    if(v==fau) continue;
    DFS(v,u);
  }
  buc1[dep[u]]+=scnt[u];
  for(int p=g1.head[u];p!=0;p=g1.graph[p].nxt){
    int v=g1.graph[p].to;
    buc2[dist[v]-dep[t[v]]+sz]++;
  }
  ans[u]+=buc1[w[u]+dep[u]]+buc2[w[u]-dep[u]+sz]-w1-w2;
  for(int p=g2.head[u];p!=0;p=g2.graph[p].nxt){
    int v=g2.graph[p].to;
    buc1[dep[s[v]]]--;
    buc2[dist[v]-dep[t[v]]+sz]--;
  }
}
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.tie(nullptr)->sync_with_stdio(false);
  std::cin>>n>>m;
  for(int cx=1,u,v;cx<n;++cx){
    std::cin>>u>>v;
    g0.addEdge(u,v),g0.addEdge(v,u);
  }
  LCADFS(1,0);
  for(int w=1;w<=std::__lg(n);++w)
    for(int cx=1;cx+(1<<w)-1<=n;++cx)
      f[w][cx]=depmin(f[w-1][cx],f[w-1][cx+(1<<(w-1))]);
  for(int cx=1;cx<=n;++cx)
    std::cin>>w[cx];
  for(int cx=1;cx<=m;++cx){
    std::cin>>s[cx]>>t[cx];
    int lca=LCA(s[cx],t[cx]);
    scnt[s[cx]]++;
    dist[cx]=dep[s[cx]]+dep[t[cx]]-(dep[lca]<<1);
    g1.addEdge(t[cx],cx),g2.addEdge(lca,cx);
    if(dep[lca]+w[lca]==dep[s[cx]])
      --ans[lca];
  }
  DFS(1,0);
  for(int cx=1;cx<=n;++cx)
    std::cout<<ans[cx]<<' ';
  return 0;
}

并查集 这里只给核心代码,使用了 std::vector,路径压缩,按秩合并,O(n+q\alpha(n))。注意初始化时赋值是否正确。

struct UnionFindSet{
  std::vector<int> fa,tsz;
  void clear(int n){ 
    fa.resize(n+1),tsz.resize(n+1,1); 
    for(int cx=0;cx<=n;++cx) fa[cx]=cx; 
  }
  int find(int n){ 
    if(fa[n]==n) return n; 
    return fa[n]=find(fa[n]); 
  }
  void merge(int u,int v){ 
    int fu=find(u),fv=find(v); 
    if(fu==fv) return;
    fa[fu]=fv,tsz[fv]+=tsz[fu]; 
  }
}UFS;

最小生成树 这里只给最好用的 Kruskal 算法的核心代码,注意此处存边仅仅是存边,并没有把图建立起来。时间复杂度 O(|E|\log |E|)。

边的存储:

struct edge{
  int u,v,w;
  friend bool operator<(const edge &a,const edge &b){
    return a.w<b.w;
  }
}edges[esz];

最小生成树边权和的求解:

std::sort(edges,edges+m);
for(int cx=0,chunkCnt=n;chunkCnt>1&&cx<m;++cx){
  int u=edges[cx].u,v=edges[cx].v;
  if(UFS.find(u)==UFS.find(v)) continue;
  ans+=edges[cx].w,UFS.merge(u,v),--chunkCnt;
}

严格次小生成树 把最小生成树求出来,然后把不在最小生成树上的边 (u,v) 放到树上替换 u 到 v 路径上的边权最大的边,更新答案。这里需要预处理一下路径上最大边权 mx 和次大边权 mx2(维护次大边权的原因是,有可能 \mathtt{mx}_{\delta(u,v)}=\underset{(x,y)\in\delta(u,v)}{\max} w_{(x,y)},只能用次大边权更新)。要对倍增和 ST 表有一定理解才能灵活地维护最大值和次大值。这样做本题,时间复杂度 O(|E| \log |E|)。洛谷数据很水,随便过,题解区有一车错解。

部落划分 其实就是求最小生成森林,要求保留 k 棵树,魔改一下最小生成树算法结束的判定即可,时间复杂度 O(|E|\log|E|)。

#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
const int sz=1e3+19;
const int esz=sz*sz;
int n,k,epp=0;
struct nedge{
  int u,v;
  double w;
  friend bool operator<(const nedge &a,const nedge &b){
    return a.w<b.w;
  }
}nedges[esz];
int v1[sz],v2[sz];
double ans[sz];
struct UnionFindSet{
  std::vector<int> fa,tsz;
  void clear(int n){
    fa.resize(n+1),tsz.resize(n+1,1);
    for(int cx=0;cx<=n;++cx) fa[cx]=cx;
  }
  int find(int n){
    if(fa[n]==n) return n;
    return fa[n]=find(fa[n]);
  }
  void merge(int u,int v){
    int fu=find(u),fv=find(v);
    if(fu==fv) return;
    fa[fu]=fv,tsz[fv]+=tsz[fu];
  }
}UFS;
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cin>>n>>k;
  for(int cx=1;cx<=n;++cx)
    std::cin>>v1[cx]>>v2[cx];
  for(int cx=1;cx<=n;++cx){
    for(int cy=1;cy<=n;++cy){
      if(cx==cy) continue;
      nedges[++epp]=nedge{cx,cy,std::hypot(v1[cx]-v1[cy],v2[cx]-v2[cy])};
    }
  }
  std::sort(nedges+1,nedges+1+epp);
  UFS.clear(n);
    for(int cx=1,chunkCnt=n,connectCnt=0;cx<=epp;++cx){
        int u=nedges[cx].u,v=nedges[cx].v;
        if(UFS.find(u)==UFS.find(v)) continue;
        UFS.merge(u,v);
        ans[++connectCnt]=nedges[cx].w;
        --chunkCnt;
        if(connectCnt==n) break;
    }
    printf("%.2lf\n",ans[n-k+1]);
  return 0;
}

货车运输 是一道最大生成树和树上倍增结合的题目,下面给一个我写的老代码,时间复杂度 O(|E|\log|E|+q\log |V|)。

#include <stdio.h>
#include <functional>
#include <algorithm>
#include <vector>
const int sz=1e4+10;
const int esz=2e4+19;
const int logsz=std::__lg(sz)+2;
const int inf=(1<<20);
int n,m,q,head[sz],hpp=0;
struct edge{
  int nxt,to,w;
}graph[esz];
void addEdge(int from,int to,int w){
  graph[++hpp]=edge{head[from],to,w};
  head[from]=hpp;
}
struct nedge{
  int u,v,w;
  bool operator>(const nedge &a)const{
    return w>a.w;
  }
};
std::vector<nedge> nedges;
struct UnionFindSet{
  std::vector<int> fa,tsz;
  void clear(int n){ 
    fa.resize(n+1),tsz.resize(n+1,1); 
    for(int cx=0;cx<=n;++cx) fa[cx]=cx; 
  }
  int find(int n){ 
    if(fa[n]==n) return n; 
    return fa[n]=find(fa[n]); 
  }
  void merge(int u,int v){ 
    int fu=find(u),fv=find(v); 
    if(fu==fv) return;
    fa[fu]=fv,tsz[fv]+=tsz[fu]; 
  }
}UFS;
int dep[sz],fath[sz][logsz],pathw[sz][logsz];
void lcaDFS(int u,int fau){
  dep[u]=dep[fau]+1,fath[u][0]=fau;
  for(int cx=1;cx<logsz;++cx){
    fath[u][cx]=fath[fath[u][cx-1]][cx-1];
    pathw[u][cx]=std::min(pathw[u][cx-1],pathw[fath[u][cx-1]][cx-1]);
  }
  for(int p=head[u],v;p;p=graph[p].nxt){
    v=graph[p].to;
    if(v==fau) continue;
    pathw[v][0]=graph[p].w;
    lcaDFS(v,u);
  }
}
int pQuery(int u,int v){
  if(UFS.find(u)!=UFS.find(v)) return -1;
  int res=inf;
  if(dep[u]>dep[v]) std::swap(u,v);
  for(int cx=logsz-1;~cx;--cx){
    if(dep[fath[v][cx]]>=dep[u]){
      res=std::min(res,pathw[v][cx]);
      v=fath[v][cx];
    }
  }
  if(u==v) return res;
  for(int cx=logsz-1;~cx;--cx){
    if(fath[u][cx]!=fath[v][cx]){
      res=std::min({res,pathw[u][cx],pathw[v][cx]});
      u=fath[u][cx],v=fath[v][cx];
    }
  }
  res=std::min({res,pathw[u][0],pathw[v][0]});
  return res;
}
int main(){
  scanf("%d%d",&n,&m);
  for(int cx=0,u,v,w;cx<m;++cx){
    scanf("%d%d%d",&u,&v,&w);
    nedges.push_back(nedge{u,v,w});
  }
  std::sort(nedges.begin(),nedges.end(),std::greater<nedge>());
  UFS.clear(n);
  for(int cx=0,chunkCnt=n;cx<m&&chunkCnt!=1;++cx){
    int u=nedges[cx].u,v=nedges[cx].v;
    if(UFS.find(u)==UFS.find(v)) continue;
    UFS.merge(u,v);
    chunkCnt--;
    addEdge(u,v,nedges[cx].w);
    addEdge(v,u,nedges[cx].w);
  }
  for(int cx=1;cx<=n;++cx){
    if(dep[cx]) continue;
    dep[cx]=1,fath[cx][0]=cx,pathw[cx][0]=inf;
    lcaDFS(cx,0);
  }
  scanf("%d",&q);
  while(q--){
    int u,v;
    scanf("%d%d",&u,&v);
    printf("%d\n",pQuery(u,v));
  }
  return 0;
}

最小公倍树 我参加 THUPC2022 初赛时折戟的一道题目,当时不敢猜结论,怕给队伍加罚时,结果后来发现我的结论离正解差一点,不过赛时即使写了这代码我估计还是过不了吧。枚举 x\in[2,r] \cap P 找到其倍数 px,使 px 为大于等于 l 的最小者,然后将 x 与 [l,r] 上除了 px 以外的所有倍数连边,即建边 (px,(p+1)x),(px,(p+2)x),\cdots。可以证明这样建图,|E|=O((r-l)\log (r-l)),跑最小生成树算法即可,时间复杂度 O((r-l)\log^2(r-l))。(以上是错解,下面是正确代码)

#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
#include <queue>
using ll=long long;
int l,r;
ll ans=0;
struct UnionFindSet{
  std::vector<int> fa,tsz;
  void clear(int n){
    fa.resize(n+1),tsz.resize(n+1,1);
    for(int cx=0;cx<=n;++cx) fa[cx]=cx;
  }
  int find(int n){
    if(fa[n]==n) return n;
    return fa[n]=find(fa[n]);
  }
  void merge(int u,int v){
    int fu=find(u),fv=find(v);
    if(fu==fv) return;
    fa[fu]=fv,tsz[fv]+=tsz[fu];
  }
}UFS;
struct item{
  int id,x,y;
  ll val;
  friend bool operator>(const item &a,const item &b){
    return a.val>b.val;
  }
};
std::priority_queue<item,std::vector<item>,std::greater<item>> pq;
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>l>>r;
  for(int cx=1;cx<=r-l;++cx){
    int x=(l+cx-1)/cx*cx,y=x+cx;
    if(y<=r) pq.push(item{cx,x,y,1LL*x*y/cx});
  }
  UFS.clear(r);
  for(int cx=1;cx<=r-l;++cx){
    auto cur=pq.top();
    pq.pop();
    while(UFS.find(cur.x)==UFS.find(cur.y)){
      cur.y+=cur.id;
      if(cur.y<=r) cur.val=1LL*cur.x*cur.y/cur.id,pq.push(cur);
      cur=pq.top(),pq.pop();
    }
    ans+=cur.val;
    UFS.merge(cur.x,cur.y);
    cur.y+=cur.id;
    if(cur.y<=r) cur.val=1LL*cur.x*cur.y/cur.id,pq.push(cur);
  }
  std::cout<<ans<<std::endl;
  return 0;
}

Day 4

参考资料
例题链接

如果觉得上午的题太简单的话就对了,想必昨天 LCA 和树上差分的练习有点多吧,那就今天上午 \overset{\mathtt{upsolve}}{补一补题} 吧。

标准代码

拓扑排序 模板的核心代码我就放在这里,inDeg 维护的是每个点的入度,topoOrd 记录的是拓扑序,函数返回值是本图是否是一个 DAG,当本图是 DAG 时将返回真,否则返回假,时间复杂度 O(|V|+|E|)。

bool topoSort(){
  std::queue<int> qq;
  int topocnt=0;
  for(int cx=1;cx<=n;++cx)
    if(inDeg[cx]==0) qq.push(cx);
  while(!qq.empty()){
    int u=qq.front();
    qq.pop(),topocnt++,topoOrd.push_back(u);
    for(int p=head[u];p!=0;p=graph[p].nxt){
      inDeg[graph[p].to]--;
      if(inDeg[graph[p].to]==0) qq.push(graph[p].to);
    }
  }
  return topocnt==n;
}

排序 是典型的拓扑排序题,结合了传递闭包等算法。

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <cstdlib>
const int sz=27;
const int esz=600;
int n,m,head[sz],hpp;
struct edge{
  int nxt,to;
}graph[esz];
void addEdge(int from,int to){
  graph[++hpp]=edge{head[from],to};
  head[from]=hpp;
}
std::string relstr;
unsigned char mp[sz][sz],indeg[sz],cindeg[sz];
std::queue<int> qq;
std::vector<int> topoOrd;
int dist[sz];
int main(){
  std::cin.tie(nullptr)->sync_with_stdio(false);
  std::cout.sync_with_stdio(false);
  std::cin>>n>>m;
  for(int tt=1;tt<=m;++tt){
    std::cin>>relstr;
    addEdge(relstr[0]-'A'+1,relstr[2]-'A'+1);
    mp[relstr[0]-'A'+1][relstr[2]-'A'+1]=1;
    indeg[relstr[2]-'A'+1]++;
    for(int p=1;p<=n;++p)
      for(int cx=1;cx<=n;++cx)
        for(int cy=1;cy<=n;++cy)
          mp[cx][cy]|=mp[cx][p]&mp[p][cy];
    for(int cx=1;cx<=n;++cx){
      if(mp[cx][cx]!=0){
        std::cout<<"Inconsistency found after "<<tt<<" relations."<<std::endl;
        exit(0);
      }
    }
    int ori=0,tsl=0;
    for(int cx=1;cx<=n;++cx)
      if(indeg[cx]==0) ori=cx;
    std::copy(indeg,indeg+n+1,cindeg);
    topoOrd.clear();
    dist[ori]=0,qq.push(ori);
    while(!qq.empty()){
      int u=qq.front();
      qq.pop(),tsl++,topoOrd.push_back(u);
      for(int p=head[u];p!=0;p=graph[p].nxt){
        int v=graph[p].to;
        cindeg[v]--;
        if(cindeg[v]==0) qq.push(v),dist[v]=dist[u]+1;
      }
    }
    if(*std::max_element(dist,dist+n+1)==n-1){
      std::cout<<"Sorted sequence determined after "<<tt<<" relations: ";
      for(auto cx:topoOrd)
        std::cout<<(char)(cx+'A'-1);
      std::cout<<'.'<<std::endl;
      exit(0);
    }
  }
  std::cout<<"Sorted sequence cannot be determined."<<std::endl;
  return 0;
}

最大食物链计数、神经网络、绿豆蛙的归宿 是三道边进行拓扑排序边进行答案统计的题目,如在过程中统计食物链个数、神经元状态和边权之积、经过某点的概率。其实拓扑排序本身不难,我们求拓扑序本身也不很有用,只是为的拓扑排序过程的独特性质。不过,在之前的练习中也可以应用拓扑序本身,比如 Tree Destruction 就可以在树去掉直径后形成的森林上进行拓扑排序,然后按照拓扑序删去树上节点。

绿豆蛙的归宿 标准代码:

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <queue>
const int sz=1e5+19;
const int esz=2e5+39;
int n,m;
int head[sz],hpp=0;
struct edge{
  int nxt,to,w;
}graph[esz];
void addEdge(int from,int to,int w){
  graph[++hpp]=edge{head[from],to,w};
  head[from]=hpp;
}
int inDeg[sz],ks[sz];
double dp[sz];
void topoSort(){
  std::queue<int> q;
  q.push(n);
  while(!q.empty()){
    int u=q.front();
    q.pop();
    for(int p=head[u],v;p!=0;p=graph[p].nxt){
      v=graph[p].to;
      dp[v]+=(dp[u]+graph[p].w)/ks[v];
      --inDeg[v];
      if(inDeg[v]==0) q.push(v);
    }
  }
}
int main(){
  std::cin>>n>>m;
  for(int cx=0,u,v,w;cx<m;++cx){
    std::cin>>u>>v>>w;
    addEdge(v,u,w);
    ks[u]++,inDeg[u]++;
  }
  topoSort();
  std::cout<<std::setprecision(2)<<std::fixed;
  std::cout<<dp[1]<<std::endl;
  return 0;
}

差分约束算法 及同类习题其实都是在进行问题的转化,最终转化到了图论的模型上去。在学习图论的后期,难的不是图论算法本身,而是如何将问题转化为图论问题解决。正如下面的打油诗一样:

模拟只会猜题意,贪心只能过样例,数学上来先打表,规律一般是 DP

组合数学碰运气,计算几何瞎暴力,图论一顿套模板,数论只会 GCD

递归递推伤不起,搜索茫然 TLE,分治做得像枚举,暴力枚举数第一

那啥,上面这点都是不会的情况下才做的,一般情况下要避免纯粹使用上面的方法。

Negative Cycle 就是一道较为神奇的转化计数题,图中无负环等价于存在一组差分约束的解,分类讨论保留哪些边,不能有负环,因此在保留某边 (u,v) 之后要看看 q_u+q_{u+1}+\cdots +q_{v-1} 的值。一通讨论过后,我们进行一个动态规划即可。时间复杂度 O(n^3) 可过。

#include <iostream>
#include <algorithm>
#include <limits>
using ll=long long;
const ll inf=std::numeric_limits<ll>::max()>>1;
const int sz=509;
int n;
ll a[sz][sz],forePlus[sz][sz],dp[sz][sz],ans=inf;
int main(){
  std::cin>>n;
  for(int cx=1;cx<=n;++cx)
    for(int cy=1;cy<=n;++cy)
      if(cx!=cy) std::cin>>a[cx][cy];
  for(int cy=1;cy<=n;++cy)
    for(int cx=cy;cx!=0;--cx)
      forePlus[cx][cy]=(forePlus[cx+1][cy]+forePlus[cx][cy-1]-
                        forePlus[cx+1][cy-1]+a[cx][cy]);
  for(int cx=1;cx<=n;++cx)
    for(int cy=1;cy<=n;++cy)
      a[cx][cy]+=a[cx-1][cy]+a[cx][cy-1]-a[cx-1][cy-1];
  #define cost(x,y,z) (forePlus[y+1][x]+a[n][y]-a[n][z]-a[x][y]+a[x][z])
  for(int cx=1;cx<=n-1;++cx){
    dp[cx][0]=forePlus[1][cx];
    ans=std::min(ans,dp[cx][0]+cost(n,cx,0));
    for(int cy=1;cy<cx;++cy){
      dp[cx][cy]=inf;
      for(int cz=0;cz<cy;++cz)
        dp[cx][cy]=std::min(dp[cx][cy],dp[cy][cz]+cost(cx,cy,cz));
      ans=std::min(ans,dp[cx][cy]+cost(n,cx,cy));
    }
  }
  std::cout<<ans<<std::endl;
  return 0;
}

页面信息