http://codeforces.com/contest/1399/problem/E1
这个题主要学会如果求每个边走过的次数,和求子树个数非常像,把每个边进行编号,但是也有不同,然后再跑一遍把价值累计起来就行了
#include<bits/stdc++.h>
#define ll long long
#define ios ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
using namespace std;
const int maxn=1e5+5,INF=0x3f3f3f3f;
struct edge
{
ll to,w;
edge(ll a,ll b){
to=a;
w=b;
}
};
vector<edge>g[maxn];
ll tim[maxn],sum;
int vis[maxn],vis1[maxn];
struct cmp {
bool operator()(pair<ll, ll> a, pair<ll, ll> b) {
return (a.first-a.first/2)*a.second<(b.first-b.first/2)*b.second;
}
};
priority_queue<pair<ll, ll>,vector<pair<ll,ll>>,cmp>q;
void dfs(int cur)
{
vis[cur]=1;
if(g[cur].size()==1&&cur>1)
{
tim[cur]=1;
return ;
}
for(int i=0;i<g[cur].size();i++)
{
edge t=g[cur][i];
if(vis[t.to]==1) continue;
dfs(t.to);
tim[cur]+=tim[t.to];
//cout<<tim[cur]<<endl;
}
}
void dfs1(int cur)
{
vis1[cur]=1;
for(int i=0;i<g[cur].size();i++)
{
edge t=g[cur][i];
if(vis1[t.to]==0)
{
sum+=t.w*tim[t.to];
//cout<<sum<<endl;
q.push(make_pair(t.w,tim[t.to]));
dfs1(t.to);
}
}
}
int main()
{
ios;
int t;
cin>>t;
while(t--)
{
ll n,s,num=0;
cin>>n>>s;
for(int i=0;i<n+2;i++)
g[i].clear(),vis[i]=0,vis1[i]=0,tim[i]=0;
sum=0;
while(!q.empty())
q.pop();
for(int i=0;i<n-1;i++)
{
int x,y,w;
cin>>x>>y>>w;
g[x].push_back(edge(y,w));
g[y].push_back(edge(x,w));
}
dfs(1);
/*for(int i=1;i<=n;i++)
cout<<tim[i]<<" ";
cout<<endl;*/
dfs1(1);
//cout<<sum<<endl;
while(!q.empty())
{
if(sum>s)
{
pair<ll,ll> t=q.top();
q.pop();
q.push(make_pair(t.first/2,t.second));
sum-=(t.first-t.first/2)*t.second;
//cout<<sum<<endl;
num++;
}
else break;
}
cout<<num<<endl;
}
return 0;
}