SOJ 4583 动态规划之分组背包

Description

  Sidney想去Gandtom家玩。但Sidney家和Gandtom家之间是高低不平、坑坑洼洼的土路。所以他需要用他的背包装几袋稀的泥,在路上铺平一些干的土,使路变成平整的泥土,才能到Gandtom家见到Gandtom。 
  已知现在有袋稀的泥,第袋稀的泥的质量为。初始时,第个分组只有第袋稀的泥。接下来Sidney每一次会把质量最小(如果质量相同取编号小的)的两组稀的泥合并成一组。新的分组的质量为原来两分组质量的和,编号为原来两组稀的泥的编号的较小者的编号。 
  试求Sidney经过次操作后,第袋稀的泥在第几组中。

 

Input

第一行有一个整数,表示组数。 
每组数据第一行有两个正整数 ,。表示稀的泥的袋数与询问的次数。 
每组数据第二行有个正整数,第个代表 
接下来有行,每行有两个非负整数   
题目保证

 

Output

每组数据输出行。 
行表示Sidney经过次操作后,第袋稀的泥在第几组中。

 

Sample Input


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

 

Sample Output







1

 

Note

第一次操作后。第1、2袋稀的泥在第1组中,第3袋稀的泥在第3组中,第4袋稀的泥在第4组中,第5袋稀的泥在第5组中。 
第二次操作后。第1、2、3袋稀的泥在第1组中,第4袋稀的泥在第4组中,第5袋稀的泥在第5组中。 
第三次操作后。第1、2、3袋稀的泥在第1组中,第4、5袋稀的泥在第4组中。 
第四次操作后。第1、2、3、4、5袋稀的泥在第1组中。

 

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
using namespace std;
const int N=1e6+5;
typedef pair <int,int> P;

int F[N],w[N];
int getf(int x)
{
    if(x==F[x])
        return x;
    return F[x]=getf(F[x]);
}
int main(){
    int i,T,n,m,t,q;
    scanf("%d",&T);
    priority_queue<P, vector<P>, greater<P> > Q;
    while(T--)
    {
        while(!Q.empty())
            Q.pop();
        scanf("%d%d",&n,&m);
        for(i=1;i<=n;i++)
        {
            scanf("%d",&w[i]);
            F[i]=i;
            Q.push(P(w[i],i));
        }
        int now=0;
        for(i=1;i<=m;i++)
        {
            scanf("%d%d",&t,&q);
            for(now;now<t;now++)
            {
                P s1=Q.top();
                Q.pop();
                P s2=Q.top();
                Q.pop();
                P s3=P(s1.first+s2.first,min(s1.second,s2.second));
                Q.push(s3);
                int p1=getf(s1.second);
                int p2=getf(s2.second);
                if(p1<p2)
                    F[p2]=p1;
                else
                    F[p1]=p2;
            }
            printf("%d\n",getf(q));
        }
    }
    return 0;
}

 

posted @ 2018-04-25 18:56  87hbteo  阅读(332)  评论(0编辑  收藏  举报