折半

#include<bits/stdc++.h>
using namespace std;
const int maxn=1000010;
long long a[10010];
typedef pair<int,int> p;
map<long long ,int>MAP;
vector<p>G[maxn];
struct qq
{
    long long val,c;
    int biao;
} d[maxn];
bool cmp(qq a ,qq b)
{
    if(a.c!=b.c)
        return a.c<b.c;
    return a.biao <b.biao;
}
int check(qq a,qq b)
{
    if(a.biao==b.biao)
        return 1;
    return 0;
}
int k;
int n,m;
void dfs(long long  sum,int x,long long  anss)
{
    if(x==n/2+1)
    {
        d[k].val=sum;
        d[k].c=anss;
        d[k++].biao=0;
        return ;
    }
    dfs(sum,x+1,anss);
    for(int i=0; i<(int)G[x].size(); i++)
    {
        sum+=G[x][i].first;
        anss+=G[x][i].second;
        dfs(sum,x+1,anss);
    }
}
void dfss(long long  sum,int x,long long  anss)
{
    if(x==n+1)
    {
        d[k].val=sum;
        d[k].c=anss;
        d[k++].biao=1;
        return ;
    }
    dfss(sum,x+1,anss);
    for(int i=0; i<(int)G[x].size(); i++)
    {
        sum+=G[x][i].first;
        anss+=G[x][i].second;
        dfss(sum,x+1,anss);
    }
}
int main()
{

    int t;
    scanf("%d",&t);
    while(t--)
    {
        for(int i=0; i<30; i++)
            G[i].clear();
        scanf("%d%d",&n,&m);
        for(int i=1; i<=n; i++)
        {
            int shu;
            scanf("%d",&shu);
            for(int j=0; j<shu; j++)
            {
                int a,b;
                scanf("%d%d",&a,&b);
                G[i].push_back(make_pair(a,b));
            }
        }
        k=0;
        dfs(0,1,0);
        int nn=n-(n/2);
        dfss(0,nn/+1,0);
        sort(d,d+k,cmp);
//        for(int i=0; i<k; i++)
//            printf("%I64d %I64d %d\n",d[i].val,d[i].c,d[i].biao);

        int head=0,tail=k-1;
        long long maxx=-1;
        for(int i=0; i<k; i++)
            if(d[i].c<=m)
                maxx=max(maxx,d[i].val);
//                printf("%I64d\n",maxx);
        while(head<tail)
        {
            if(d[head].c+d[tail].c<m)
            {
                if(check(d[head],d[tail]))

                    maxx=max(maxx,d[head].val+d[tail].val);
                head++;
            }
            else if(d[head].c+d[tail].c>m)
            {
                tail--;
            }
            else
            {
                int headd=head;
                while(d[headd].c+d[tail].c==m&&headd<tail)
                {
                    if(check(d[headd],d[tail]))
                        maxx=max(maxx,d[headd].val+d[tail].val);
                    headd++;
                }

                tail--;
            }
        }
        printf("%I64d\n",maxx);
    }
}
/*
1
3 5
1 1 1
2 1 1 5 4
1 5 3
*/

沒有提交的地方,ac是否待定。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章