poj 2528 java

本文介绍了一个基于线段树的数据结构实现,用于解决特定类型的区间更新和查询问题。通过实例演示了如何创建线段树、插入区间、进行深度优先搜索等操作,并统计特定条件下区间的颜色数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.Scanner;

public class POJ_2528 {

	public static final int MAX = (int) 1e7;
	static int dist[];
	static int post[][];
	static int maxP;
	static LineTree[] LT;
	static int n;
	static int sumColor ;
	static boolean visit[]; 
	
	
	public static void main(String[] args) {
		
		Scanner scan = new Scanner(System.in);
		
		int test = scan.nextInt();
		
		for(int t=0;t<test;t++){
			dist = new int[MAX+1];
		    n = scan.nextInt();
			post = new int[n][2];
			int p[] = new int[2*n];
			maxP = 0;
			sumColor = 0;
			visit = new boolean[n+1];
			
			for(int i=0;i<n;i++){
				post[i][0] = scan.nextInt();
				post[i][1] = scan.nextInt();
				if(dist[post[i][0]]==0){
					p[maxP++] = post[i][0];
					dist[post[i][0]] = 1;
				}
				if(dist[post[i][1]]==0){
					p[maxP++] = post[i][1];
					dist[post[i][1]] = 1;
				}
			}
			
			java.util.Arrays.sort(p,0,maxP);
			
			int hash = 0;
			for(int i=0;i<maxP;i++){
				dist[p[i]] = hash++;
			}
			for(int i=0;i<n;i++){
				int a  = dist[post[i][0]];
				int b = dist[post[i][1]];
				post[i][0] = a;
				post[i][1] = b;
			}
			dist = null;
			LT = new LineTree[4*maxP];
			
			createLineTree(0,maxP-1,1);
			
			solution();
			System.out.println(sumColor);
			LT = null;
			
		}

	}


	public static void solution() {
		
		for(int i=0;i<n;i++){
			insert(post[i][0],post[i][1],1,i+1);
		}
		DFS(1);
		visit = null;
	}


	public static void DFS(int p) {
		
		if(LT[p].color==0)
			return ;
		if(LT[p].color>0){
			if(!visit[LT[p].color]){
				sumColor++;
				visit[LT[p].color] = true;
			}
			return ;
		}
		DFS(2*p);
		DFS(2*p+1);
		
	}


	public static void insert(int s, int e, int p, int color) {
		
		if(e<LT[p].s||s>LT[p].e)
			return ;
		if(s<=LT[p].s&&e>=LT[p].e){
			LT[p].color = color;
			return ;
		}
		if(LT[p].color>=0){
			LT[2*p].color = LT[2*p+1].color = LT[p].color;
			LT[p].color = -1;
		}
		insert(s,e,2*p,color);
		insert(s,e,2*p+1,color);
		
	}


	public static void createLineTree(int s, int e, int p) {
		
		LT[p] = new LineTree(s,e,0);
		if(s == e)
			return ;
		int mid = (s+e)>>1;
		createLineTree(s,mid,2*p);
		createLineTree(mid+1,e,2*p+1);
		
	}

}

class LineTree{
	int s;
	int e;
	int color;
	public LineTree(int s, int e, int color) {
		super();
		this.s = s;
		this.e = e;
		this.color = color;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值