Bob intends to color the nodes of a tree with a pen. The tree consists of xi. 
You need to help Bob to calculate the minimum energy he needs for the painting with all rules proposed by Alice satisfied. 

InputThe first line is the number of test cases. For each test case, the first line contains one positive number −1instead. 
Sample Input

2 
5
1 2
2 3
3 4
1 5
2
2 1
5 1
1
2 1
5
1 2
2 3
3 4
1 5
3
1 2
2 2
5 1
1
3 5

Sample Output

2
-1

题意:给定大小为N的树,限制点都是白色,让你染色,求最小染色数,有A+B个的限制,A限制表示X子树至少有Y个点被染色。B限制表示X子树之外的那些点,至少有Y个点被染色。

思路:很难想到二分答案。根据A条件我们可以得到每个子树至少有多少个点染色;二分之后,根据B条件,我们可以得到子数最多有多少个染色点,然后看每个点是否有矛盾,如果有矛盾,或者整棵树不够染色,输出-1。是否二分成立。

#include<bits/stdc++.h>
#define pb push_back
#define feach(i,u) for(int i=0,L=G[u].size();i<L;i++)
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define Gv G[u][i]
using namespace std;
const int maxn=100010;
vector<int>G[maxn];
int A,B,x[maxn],y[maxn];
int Mn[maxn],Mx[maxn],sz[maxn],N;
bool dfs1(int u,int f)
{
    sz[u]=1; int tmp=0;
    feach(i,u) {
        if(Gv==f) continue;
        dfs1(Gv,u);
        sz[u]+=sz[Gv];
        tmp+=Mn[Gv];
    }
    Mn[u]=max(Mn[u],tmp);
}
bool dfs(int u,int f)
{
    int tmp=0;
    feach(i,u) {
        if(Gv==f) continue;
        if(!dfs(Gv,u)) return false;
        tmp+=Mx[Gv];
    }
    Mx[u]=min(Mx[u],tmp+1);
    if(Mx[u]<Mn[u]) return false;
    return true;
}
bool check(int Mid)
{
    rep(i,1,N) Mx[i]=sz[i];
    rep(i,1,B) Mx[x[i]]=min(Mx[x[i]],Mid-y[i]);
    if(dfs(1,0)&&Mx[1]>=Mid) return true;
    return false;
}
int main()
{
    int T,u,v,w,e;
    scanf("%d",&T);
    while(T--){
        scanf("%d",&N);
        rep(i,1,N) G[i].clear(),Mn[i]=0;
        rep(i,1,N-1) {
            scanf("%d%d",&u,&v);
            G[u].pb(v); G[v].pb(u);
        }
        scanf("%d",&A);
        rep(i,1,A){
            scanf("%d%d",&w,&e);
            Mn[w]=max(Mn[w],e);
        }
        dfs1(1,0);
        scanf("%d",&B);
        rep(i,1,B) scanf("%d%d",&x[i],&y[i]);
        int L=Mn[1],R=N,ans=-1,Mid;
        while(L<=R){
            Mid=(L+R)/2;
            if(check(Mid)) ans=Mid,R=Mid-1;
            else L=Mid+1;
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

相关文章: