poj java 提交_POJ 1986 java代码实现

package pro.yao10_16LCA;

import java.util.*;

import java.io.*;

/**

7 6

1 6 13 E

6 3 9 E

3 5 7 S

4 1 3 N

2 4 20 W

4 7 2 S

3

1 6

1 4

2 6

* @author XASW

*

*/

public class Main {

static int T,N,Q,S,E,W,set[],vis[],D[],first[];

static Node[] nodes;

static List arrayV[];

public static void main(String[] args) throws Exception{

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

StringTokenizer st = new StringTokenizer(bf.readLine());

N = Integer.valueOf(st.nextToken());

Q = Integer.valueOf(st.nextToken());

arrayV = new ArrayList[N+1];

nodes = new Node[Q*2 +2];

set = new int[N+1];

vis = new int[N+1];

D = new int[N+1];

first = new int[N+1];

for (int i = 0; i < N+1; i++) {

arrayV[i] = new ArrayList();

set[i] = i;

first[i] = -1;

}

for (int i = 0; i < Q *2 +2; i++) {

nodes[i] = new Node();

}

for (int i = 1; i <= Q; i++) {

st = new StringTokenizer(bf.readLine());

S = Integer.valueOf(st.nextToken());

E = Integer.valueOf(st.nextToken());

W = Integer.valueOf(st.nextToken());

arrayV[S].add(new Integer[] {E,W});

arrayV[E].add(new Integer[] {S,W});

}

st = new StringTokenizer(bf.readLine());

Q = Integer.valueOf(st.nextToken());

for (int i = 0; i < Q; i++) {

st = new StringTokenizer(bf.readLine());

S = Integer.valueOf(st.nextToken());

E = Integer.valueOf(st.nextToken());

add(S,E,i*2);

add(E,S,i*2+1);

}

D[1] = 0;

tarjan(1);

for (int i = 0; i < Q; i++) {

int id = i*2;

int u = nodes[id].from;

int v = nodes[id].to;

int lca = nodes[id].lca;

System.out.println(D[u] + D[v]-2*D[lca]);

}

}

static void tarjan(int u) {

vis[u] = 1;

for (int i = 0; i < arrayV[u].size(); i++) {

Integer[] s = arrayV[u].get(i);

if(vis[s[0]]==1) continue;

D[s[0]] = D[u]+s[1];

tarjan(s[0]);

join(s[0],u);

}

for (int i = first[u]; i != -1; i=nodes[i].next) {

int v = nodes[i].to;

if(vis[v]==0)continue;

nodes[i].lca = nodes[i^1].lca = find(v);

}

}

static void add(int u,int v,int cnt) {

nodes[cnt].to = v;

nodes[cnt].from = u;

nodes[cnt].next = first[u];

first[u] = cnt;

}

static int find(int a) {

if(set[a] == a) {

return set[a];

}

return set[a] = find(set[a]);

}

static void join(int a,int b) {

int A = find(a);

int B = find(b);

if(A!=B) {

set[A] = B;

}

}

static class Node{

int from;

int to;

int next;

int lca;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值