HDU-2795 線段樹

由於題目給的公告數最多是200000,所以最多也就用200000行。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main_HDU2795{
	static int[] Tr = new int[200005<<2];  //用行做數組長度
	static PrintWriter out = new PrintWriter(System.out);
	public static void main(String[] args) {
		InputReader2795 sc = new InputReader2795();
		while(sc.hasNext()) {
			int h = sc.nextInt();
			int w = sc.nextInt();
			int n = sc.nextInt();
			if(h>n) h = n;  //因爲最多的公告數只有200000 所以只能用到200000行
			build(1,h,1);
			for(int i=1;i<=n;i++) {
				int wi = sc.nextInt();
				if(Tr[1]+wi>w) {  //用的最短的行都超過了
					out.println(-1);
				}else {
					query(wi,w,1,h,1);
				}
			}
			out.flush();
		}
	}
	public static void build(int l,int r,int root) {
		Tr[root] = 0;
		if(l==r) return;
		int m = (l+r)>>1;
		build(l,m,root<<1);
		build(m+1,r,root<<1|1);
	}
	public static void query(int wi,int w,int l,int r,int root) {
		if(l==r) {
			out.println(l);
			Tr[root] += wi;
			return;
		}
		int m = (l+r)>>1;
		if(Tr[root<<1]+wi<=w) {     
			query(wi,w,l,m,root<<1);
		}else {
			query(wi,w,m+1,r,root<<1|1);
		}
		Tr[root] = Math.min(Tr[root<<1], Tr[root<<1|1]);
	}
}
class InputReader2795
{
    BufferedReader buf;
    StringTokenizer tok;
    InputReader2795()
    {
        buf = new BufferedReader(new InputStreamReader(System.in));
    }
    boolean hasNext()
    {
        while(tok == null || !tok.hasMoreElements()) 
        {
            try
            {
                tok = new StringTokenizer(buf.readLine());
            } 
            catch(Exception e) 
            {
                return false;
            }
        }
        return true;
    }
    String next()
    {
        if(hasNext()) return tok.nextToken();
        return null;
    }
    int nextInt()
    {
        return Integer.parseInt(next());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章