HDU 3974 Assign the task (并查集 || 线段树)

题目链接

虽然挂在线段树的题集里,但是能一眼看出也是并查集的题。本来准备就用线段树做,可是,想了半天不知道怎么建树。。。就先用并查集过吧。等忙完期末项目,回来再看看怎么用线段树做。


并查集代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
	static Scanner sc = new Scanner(System.in);
	static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	static int T,n,m,newTime,newTask;
	static int [] dad;
	static int [] mis;
	static int [] tim;
	static void find(int x){
		while(dad[x] != x){
			if(newTime < tim[x]){//newTime小则应跟随大的时间更新
				newTime = tim[x];
				newTask = mis[x];
			}
			x = dad[x];
		}
		if(newTime < tim[x]){//与最终boss比较
			newTime = tim[x];
			newTask = mis[x];
		}
	}
	public static void main(String[] args) throws IOException {
		T = sc.nextInt();
		for(int t = 1; t <= T; t++){
			System.out.println("Case #"+t+":");
			n = sc.nextInt();
			dad = new int[n+1];
			for(int i = 1; i <= n; i++)
				dad[i] = i;
			mis = new int[n+1];
			Arrays.fill(mis, -1);
			tim = new int[n+1];
			Arrays.fill(tim, 0);
			int u,v;
			for(int i = 0; i < n - 1; i++){
				u = sc.nextInt(); v = sc.nextInt();
				dad[u] = v;
			}
			m = sc.nextInt();
			String op;
			int emp,task,k = 0;
			for(int i = 0; i < m; i++){
				op = sc.next();
				if(op.equals("C")){
					emp = sc.nextInt();
					newTime = 0;
					newTask = mis[emp];
					find(emp);
					System.out.println(newTask);
				}
				else{
					emp = sc.nextInt(); task = sc.nextInt();
					mis[emp] = task;
					tim[emp] = ++k;
				}
			}
		}

	}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值