题目链接:
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1307
题意:
题解:
方法一:
因为所有绳子最终组成了1棵树,所以我们可以通过一次DFS,来检测是否有某根绳子下面绑了超过他所能负荷的重量。
具体方法:对每个节点,计算其子树的重量和(包含自身的重量),如果大于能承受的最大重量,则绳子会断,否则不会断。
一次DFS时间复杂度是O(n)的。
既然一次判断的复杂度是O(n)的,并且当绳子第一次断掉后,继续放重物,不会改变绳子断掉的状态(毕竟重物的重量都是正数,没有负数),那么我们可以用二分来做。
二分来求第一次断掉的点,由于二分的复杂度是log(n),一次DFS判断的复杂度是O(n),所以整个算法的复杂度是nlog(n)。
二分经常被用来求解一些具有单调性的问题,这里的单调性就是断掉以后,不会再次变成不断的。
方法二:
我们在DFS的过程中,使用并查集,将子树节点的Root指向当前节点,同时计算子树的总重量。
假如当前节点的承重不足,那么绳子会断掉。所以我们需要去掉一些节点,来保证绳子不断。根据题目要求,我们按照子树节点的编号从高到低,逐个去掉这些重物,直到绳子不断为止。
那么问题来了,并查集这个结构并不能解决按照编号从高到低去掉子树的问题,如果自己维护其他的数据结构(比如堆),恐怕复杂度还要多一个Log。
所以我们跳出按照编号从高到低去掉子树的思路,不如直接从编号N - 1到0去掉子树,直到当前的绳子不断为止。 因为编号小的断了,后面再加的绳子也没有用了,已经有绳子断了就结束了。
代码:
二分:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;
struct node{
int c,w,f;
}e[maxn];
vector<int> g[maxn];
bool book;
ll dfs(int u,int k){
ll sum = e[u].w;
if(u > k) return 0;
for(auto v : g[u])
sum += dfs(v,k);
if(sum > e[u].c && u) book = false;
return sum;
}
int main(){
int n=read();
for(int i=1; i<=n; i++){
e[i].c=read(); e[i].w=read(); e[i].f=read(); e[i].f++;
g[e[i].f].push_back(i);
}
int l=0,r=n,ans = 0;
while(l<=r){
int mid = (l+r)/2;
book = true;
dfs(0,mid);
if(book) ans=mid,l=mid+1;
else r=mid-1;
}
cout << ans << endl;
return 0;
}
并查集:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;
struct node{
ll c,w,f;
}e[maxn];
vector<int> g[maxn];
int fa[maxn];
ll ww[maxn];
int k;
int find(int x){
return fa[x]==x ? x : fa[x]=find(fa[x]);
}
void update(int u){
for(auto v : g[u]){
e[u].w += e[v].w;
fa[v] = u;
}
while(e[u].w > e[u].c){
e[find(k)].w -= ww[k];
k--;
}
}
int main(){
int n=read();
for(int i=1; i<=n; i++){
e[i].c=read(); e[i].w=read(); e[i].f=read(); e[i].f++;
g[e[i].f].push_back(i); ww[i] = e[i].w;
fa[i] = i;
}
k = n;
for(int i=n; i>0; i--)
update(i);
cout << k << endl;
return 0;
}