您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
今天就跟大家聊聊有关如何理解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<Integer[]> 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<Integer[]>(); 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; } }
看完上述内容,你们对如何理解POJ 1986 java代码实现有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。