zoukankan      html  css  js  c++  java
  • [Codeforces543D]Road Improvement

    Problem

    刚开始每条边都是坏的,现在要选取一个点使得其他点到这个点的路径上最多只有一条坏路,问至少要修好多少条边

    Solution

    如果以1为根,那么是个简单的树形DP
    设根从u转移到v,那么u的父亲会变成v(f[u]需要删除v的贡献),
    u的原来的父亲会变成u的孩子(f[u]需要加上原父亲的贡献),
    v会成为u的父亲(f[v]加上u的贡献)。
    这样从上向下转移即可。

    Notice

    注意F值的备份和还原

    Code

    #include<cmath>
    #include<deque>
    #include<vector>
    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    #define sqz main
    #define ll long long
    #define reg register int
    #define rep(i, a, b) for (reg i = a; i <= b; i++)
    #define per(i, a, b) for (reg i = a; i >= b; i--)
    #define travel(i, u) for (reg i = head[u]; i; i = edge[i].next)
    const int INF = 1e9, N = 200000, mo = INF + 7;
    const double eps = 1e-6, phi = acos(-1);
    ll mod(ll a, ll b) {if (a >= b || a < 0) a %= b; if (a < 0) a += b; return a;}
    ll read(){ ll x = 0; int zf = 1; char ch; while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
    if (ch == '-') zf = -1, ch = getchar(); while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return x * zf;}
    void write(ll y) { if (y < 0) putchar('-'), y = -y; if (y > 9) write(y / 10); putchar(y % 10 + '0');}
    vector<int> edge[N + 5], Left[N + 5], Right[N + 5];
    int ans[N + 5], f[N + 5], fa[N + 5], num = 0;
    void dp(int u)
    {
    	f[u] = 1;
    	for(auto v : edge[u])
    	{
    		fa[v] = u;
    		dp(v);
    		f[u] = (long long)f[u] * (f[v] + 1) % mo;
    	}
    	int l = 1, r = 1;
    	for(auto i = edge[u].begin(); i != edge[u].end(); i++)
    	{
    		Left[u].push_back(l);
    		l = (ll)l * (f[*i] + 1) % mo;
    	}
    	for(auto i = edge[u].rbegin(); i != edge[u].rend(); i++)
    	{
    		Right[u].push_back(r);
    		r = (ll)r * (f[*i] + 1) % mo;
    	}
    	reverse(Right[u].begin(), Right[u].end());
    }
    void dfs(int u)
    {
    	ans[u] = f[u];
    	for(auto i = 0; i < edge[u].size(); i++)
    	{
    		int v = edge[u][i], uu = f[u], vv = f[v];
    		f[u] = (ll)Left[u][i] * Right[u][i] % mo * (f[fa[u]] + 1) % mo;
    		f[v] = (ll)f[v] * (f[u] + 1) % mo;
    		dfs(v);
    		f[u] = uu, f[v] = vv;
    	}
    }
    int sqz()
    {
    	int n = read();
    	rep(i, 2, n) edge[read()].push_back(i);
    	fa[1] = 0;
    	f[0] = 0;
    	dp(1);
    	dfs(1);
    	rep(i, 1, n) printf("%d%c", ans[i], i == n ? '
    ' : ' ');
    }
    
  • 相关阅读:
    Java内存区域
    高并发
    集合框架
    面向对象基础概念
    java synchronized详解
    java使用DOM操作XML
    二、认识Xcode(第一个工程:Hello world)
    菜鸟手下的iOS开发笔记(swift)
    一、iOS开发环境搭建
    一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(十)使用JRTPLIB传输RTP数据
  • 原文地址:https://www.cnblogs.com/WizardCowboy/p/7764962.html
Copyright © 2011-2022 走看看