Codeforces Round #661 (Div. 3) E2. Weights Division (hard version)

传送门

题意:给你一颗带权树,现在定义 s = 根到所有叶子的路径和。现有S,你现在可以将每条边的权值 / 2,对不同的边进行除2操作有不同的费用(1或者2),现在求最小的花费,使s <= S。

思路:第一印象是二分答案,但枚举答案并没有什么用。

我们这样思考,最后的花费无非就是进行x次费用1的操作,y次费用2的操作,那么,我们可以事先计算好进行i次费用1操作所能减少的最大值,j次费用2操作所能减少的最大值,然后枚举其中一个的个数 另外一个可以用二分找到能满足要求的最小的次数。

发现这种对结果只有两种贡献的问题 枚举其中一个 这种思路比较有效。

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

#define lsn (u << 1)
#define rsn (u << 1 | 1)
#define mid (l + r >> 1)

typedef long long ll;
typedef unsigned long long ull;

typedef pair<int, int> P;

const int MAXN = 4e6 + 10;
const int MAX_LEN = 100000 + 10;
const int MAX_LOG_V = 22;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-7;
const ull B = 100000007;
inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }while ('0' <= ch && ch <= '9') { x = x * 10; x += ch - '0'; ch = getchar(); }return x * f; }


struct edge { int to, cost, coin; };
struct Node {
	ll cnt, w;
	bool operator < (const Node &b) const {
		return (w-w/2)*cnt < (b.w-b.w/2)*b.cnt;
	}
};

vector<edge> g[MAXN];
priority_queue<Node> q1, q2;

int n;
int vis[MAXN];
ll v1[MAXN], v2[MAXN];
ll S, sum;


int dfs(int v, int p) {
	if(vis[v]) return 1;
	int cnt = 0;
	for(int i = 0; i < g[v].size(); i++) {
		edge &e = g[v][i];
		if(e.to == p) continue;
		int t = dfs(e.to, v);
		sum += 1ll * t * e.cost;
		cnt += t;
		if(e.coin == 1) q1.emplace(Node{t, e.cost});
		else q2.emplace(Node{t, e.cost});
	}
	return cnt;
}

void cal(ll *v, priority_queue<Node> &q, int &tot) {
	for(int i = 1; !q.empty(); i++) {
		Node p = q.top(); q.pop();
		v[i] = v[i-1] + (p.w-p.w/2)*p.cnt;
		if(v[i] == v[i-1]) break;
		p.w /= 2; q.emplace(p);
		tot = i;
	}
}

void sovle() {
	scanf("%d %lld", &n, &S);
	while(!q1.empty()) q1.pop();
	while(!q2.empty()) q2.pop();
	sum = 0;
	for(int i = 1; i <= n; i++) { g[i].clear(); vis[i] = 0; }  
	for(int i = 1; i < n; i++) {
		int u, v, w, c;
		scanf("%d %d %d %d", &u, &v, &w, &c);
		g[u].emplace_back(edge{v, w, c});
		g[v].emplace_back(edge{u, w, c});
	}
	for(int i = 2; i <= n; i++) {
		if(g[i].size() == 1) vis[i] = 1;
	} 
	dfs(1, 0);
	int tot1 = 0, tot2 = 0;
	cal(v1, q1, tot1); 
	cal(v2, q2, tot2);
	ll d = sum - S;
	if(d <= 0) { puts("0"); return ; }
	int ans = INF;
	int j = tot2;
	for(int i = 0; i <= tot1; i++) {
		while(j > 0 && v1[i] + v2[j - 1] >= d) --j;
		if(v1[i] + v2[j] >= d) {
			ans = min(ans, i + j * 2);
		}
	}
	printf("%d\n", ans);
}


int main() {
	int t = 1; scanf("%d", &t);
	while(t--) {
		sovle();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值