题解:P11179 [ROIR 2018] 管道监控 (Day1)

博客园

简单题。

乍一看不可做,但是发现 \(n=500\),并且路径只能从上往下走,于是可以对所有规格建出 Trie 树,然后原树上一遍 dfs 求出所有操作的权值。

然后就是简单树形 DP,把所有操作挂在深度最大的点上,设 \(dp_{i,j}\) 表示处理了 \(i\) 的子树内的操作后,覆盖了 \(j\) 条祖先边时的最小权值。转移是一个 \((\min,+)\) 卷积,贡献到下标 \(\max\),可以通过枚举下标 \(\max\) 做到 \(\mathcal O(n)\),总复杂度 \(\mathcal O(n^2)\)。

题目要求输出方案,那么在转移时记录最优决策的下标 \(\max\) 出现在哪里和每个操作的编号即可。最终复杂度 \(\mathcal O(n^2+\sum\text{len}(st_k))\)。

#include <bits/stdc++.h>
using namespace std;
#define ll long long
constexpr int N=5e2+2,M=1e6+6;
constexpr ll inf=0x3f3f3f3f3f3f3f;
int n,m,c,fa[N];
pair<ll,int>dp[N][N],f[N][N],val[M],t[N][N];
int nxt[M][26],cnt;
char fp[N];
string s;
void insert(string s,int v,int id){
    int p=0;
    for(char c:s){
        if(!nxt[p][c-'a'])val[nxt[p][c-'a']=++cnt]={inf,0};
        p=nxt[p][c-'a'];
    }val[p]=min(val[p],{v,id});
}
int dep[N];
vector<int>e[N];
void dfs1(int p){for(int x:e[p])dep[x]=dep[p]+1,dfs1(x);}
void work(int p,int pos,int d){
    f[p][d]=val[pos];
    for(int x:e[p])if(nxt[pos][fp[x]-'a'])work(x,nxt[pos][fp[x]-'a'],d+1);
}
void dfs2(int p){work(p,0,0);for(int x:e[p])dfs2(x);}
ll t1[N];
void dfs3(int p){
    for(int x:e[p])dfs3(x);
    for(int i=0;i<=dep[p];i++)t1[i]=0;
    for(int x:e[p])for(int i=0;i<=dep[p];i++)t1[i]+=t[x][i+1].first;
    for(int i=0;i<=dep[p];i++)dp[p][i]={t1[i]+f[p][i].first,p};
    for(int x:e[p])for(int i=0;i<=dep[p];i++)dp[p][i]=min(dp[p][i],{t1[i]-t[x][i+1].first+dp[x][i+1].first,x});
    t[p][0]={inf,0};
    for(int i=1;i<=dep[p];i++)t[p][i]=min(t[p][i-1],{dp[p][i].first,i});
}
struct A{int x,len,id;};
vector<A>res;
void work(int p,int h){
    if(dp[p][h].second==p)res.push_back({p,h,f[p][h].second});
    for(int x:e[p]){
        if(x==dp[p][h].second)work(x,h+1);
        else work(x,t[x][h+1].second);
    }
}
void _main(){
    cin>>n>>m>>c;
    for(int i=2;i<=n;i++)cin>>fa[i]>>fp[i],e[fa[i]].push_back(i);
    val[0]={inf,0};
    for(int i=1,x;i<=m;i++)cin>>x>>s,insert(s,x,i);
    for(int i=1;i<=n;i++)for(int j=0;j<=n;j++)f[i][j]={inf,0};
    dfs1(1),dfs2(1),dfs3(1);
    if(dp[1][0].first>1e9*n)cout<<"-1\n";
    else{
        cout<<dp[1][0].first<<'\n';
        if(c){
            work(1,0);
            cout<<res.size()<<'\n';
            for(auto x:res){
                int p=x.x;
                for(int j=1;j<=x.len;j++)p=fa[p];
                cout<<p<<' '<<x.x<<' '<<x.id<<'\n';
            }
        }
    }
}
signed main(){
    clock_t _st=clock();
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    int t=1;
    while(t--)_main();
    clock_t _ed=clock();
    cerr<<(_ed-_st)*1.0/CLOCKS_PER_SEC<<'\n';
    return 0;
}
posted @ 2026-09-09 14:55  Redolent  阅读(19)  评论(0)    收藏  举报