@@ -25,7 +25,7 @@ public class Code03_Envy1 {
2525 // 节点u、节点v、边权w
2626 public static int [][] edge = new int [MAXN ][3 ];
2727 // 节点u、节点v、边权w、问题编号i
28- public static int [][] queryEdge = new int [MAXN ][4 ];
28+ public static int [][] queries = new int [MAXN ][4 ];
2929
3030 // 可撤销并查集
3131 public static int [] father = new int [MAXN ];
@@ -70,28 +70,33 @@ public static void prepare() {
7070 siz [i ] = 1 ;
7171 }
7272 Arrays .sort (edge , 1 , m + 1 , (a , b ) -> a [2 ] - b [2 ]);
73- Arrays .sort (queryEdge , 1 , k + 1 , (a , b ) -> a [2 ] != b [2 ] ? (a [2 ] - b [2 ]) : (a [3 ] - b [3 ]));
73+ Arrays .sort (queries , 1 , k + 1 , (a , b ) -> a [2 ] != b [2 ] ? (a [2 ] - b [2 ]) : (a [3 ] - b [3 ]));
7474 Arrays .fill (ans , 1 , q + 1 , true );
7575 }
7676
7777 public static void compute () {
78- int ei = 1 ;
78+ int ei = 1 , queryId , unionCnt ;
7979 for (int l = 1 , r = 1 ; l <= k ; l = ++r ) {
80- for (; ei <= m && edge [ei ][2 ] < queryEdge [l ][2 ]; ei ++) {
80+ while (r + 1 <= k && queries [l ][2 ] == queries [r + 1 ][2 ] && queries [l ][3 ] == queries [r + 1 ][3 ]) {
81+ r ++;
82+ }
83+ // 添加小于当前边权的边,利用Kruskal算法增加连通性,ei是不回退的
84+ for (; ei <= m && edge [ei ][2 ] < queries [l ][2 ]; ei ++) {
8185 if (find (edge [ei ][0 ]) != find (edge [ei ][1 ])) {
8286 union (edge [ei ][0 ], edge [ei ][1 ]);
8387 }
8488 }
85- while (r + 1 <= k && queryEdge [l ][2 ] == queryEdge [r + 1 ][2 ] && queryEdge [l ][3 ] == queryEdge [r + 1 ][3 ]) {
86- r ++;
89+ queryId = queries [l ][3 ];
90+ if (!ans [queryId ]) {
91+ continue ;
8792 }
88- int unionCnt = 0 ;
93+ unionCnt = 0 ;
8994 for (int i = l ; i <= r ; i ++) {
90- if (find (queryEdge [i ][0 ]) == find (queryEdge [i ][1 ])) {
91- ans [queryEdge [ i ][ 3 ] ] = false ;
95+ if (find (queries [i ][0 ]) == find (queries [i ][1 ])) {
96+ ans [queryId ] = false ;
9297 break ;
9398 } else {
94- union (queryEdge [i ][0 ], queryEdge [i ][1 ]);
99+ union (queries [i ][0 ], queries [i ][1 ]);
95100 unionCnt ++;
96101 }
97102 }
@@ -126,10 +131,10 @@ public static void main(String[] args) throws IOException {
126131 for (int j = 1 , ei ; j <= s ; j ++) {
127132 in .nextToken ();
128133 ei = (int ) in .nval ;
129- queryEdge [++k ][0 ] = edge [ei ][0 ];
130- queryEdge [k ][1 ] = edge [ei ][1 ];
131- queryEdge [k ][2 ] = edge [ei ][2 ];
132- queryEdge [k ][3 ] = i ;
134+ queries [++k ][0 ] = edge [ei ][0 ];
135+ queries [k ][1 ] = edge [ei ][1 ];
136+ queries [k ][2 ] = edge [ei ][2 ];
137+ queries [k ][3 ] = i ;
133138 }
134139 }
135140 prepare ();
0 commit comments