We are given a graph with N nodes (planets) and M edges (spaceways), which are bidirectional. Additionally, we have the ability to add teleports (edges) between any pair of planets, but each teleport endpoint incurs a cost: for a planet i, if we choose to make a teleport that ends at i, then we have to pay (or receive) C_i. However, the description is ambiguous: what exactly does "make a teleport ending at their planet" mean? Usually, when we add a teleport between two planets, both endpoints are used; do we pay the cost for both planets? Or is it that each teleport we create costs the sum of the costs of the two planets? Or maybe we are allowed to create teleports arbitrarily, but each planet that we choose to include as an endpoint (i.e., that we connect via teleport) incurs a cost C_i, regardless of how many teleports connect to it? Let's read carefully.
Problem statement:
"There are two types of governments ... So each of these government has asked the GFA for a tax value which it has to pay if it wants to make a teleport ending at their planet."
Similarly, type 2 pays the GFA if they make a teleport ending at their planet.
Now: "Now, the GFA wants to make bi-directional teleports between planets such that the football teams of any planet can reach any other planet to play a football match, using spaceways between the planets and/or teleports made by the GFA."
So they can add teleport edges. The cost structure: each teleport is bidirectional; presumably, if we add a teleport between planets u and v, then that teleport "ends" at both u and v. So we would need to pay the tax (or receive sponsorship) for both endpoints? Or maybe the phrase "ending at their planet" means that each planet that has a teleport endpoint attached (i.e., it is incident to at least one teleport) incurs a cost C_i (if positive, we pay; if negative, they pay us, but we want to avoid negative because it's type 2 and they have dirty plans?). Actually: "The GFA would always avoid such governments no matter what the consequences are, because these kind of governments have always some dirty plans in their minds for the GFA." So the GFA wants to avoid type 2 governments; i.e., they don't want to accept sponsorship money? But they want to minimize money spent; if they could get money from them, that would reduce cost. But the statement says they always avoid such governments no matter what the consequences are. That suggests that they are not willing to accept the money; they would rather not have teleport endpoints at those planets. But is it forced? Let's read: "Now, the GFA wants to make bi-directional teleports between planets ... The GFA also has financial problems and want to spend as little money as possible." So presumably, they want to minimize cost; if some planets offer negative cost (i.e., they give money), then including them would reduce cost. However, the statement says: "The GFA would always avoid such governments no matter what the consequences are, because these kind of governments have always some dirty plans in their minds for the GFA." That suggests they are not willing to take the risk; so they would not consider teleports ending at those planets. But then why mention that they give money? It could be that they are forced to avoid them, meaning they cannot use teleports that involve those planets. But the problem asks to compute minimum amount needed; if they avoid them, then the solution would never include teleports on type2 planets, and we just treat those planets as having infinite cost or not allowed? But the sample may clarify.
Sample 1:
N=6, M=6 edges: (1-2,2-3,1-3) and (4-5,5-6,4-6). So two separate triangles (three nodes each) fully connected within themselves. So the graph has two connected components: {1,2,3} and {4,5,6}. Costs:
1:1
2:3
3:5
4:2
5:4
6:6
All positive (type1). So all planets have tax >0. They need to add teleports to connect the two components. They can add teleports between any pair. Each teleport has a cost? The answer is 3. How to get 3? If we add a teleport between 1 and 4, costs: at planet 1 we pay 1, at planet 4 we pay 2, total 3. That yields total cost 3. That matches answer. So it seems cost of adding a teleport between u and v is C_u + C_v. Also note that we could add multiple teleports, but we only need one to connect the components, so that's minimal. So cost is sum of endpoint costs.
But could there be a situation where we need to add multiple teleports, and perhaps we could use a planet multiple times? Does the cost per endpoint incur only once if that planet is used in multiple teleports? The phrasing "if it wants to make a teleport ending at their planet" suggests that each teleport that ends at a planet incurs the cost. But is it per teleport? Or per planet? In typical problems like "building airports" where each node has a cost to open an airport and edges (flights) can be added connecting airports, you pay cost per node to "open" it, and then you can connect opened nodes with zero cost edges. But here teleports are added between planets, and each teleport incurs cost at its endpoints. If you use a planet for multiple teleports, do you pay the tax multiple times? Likely not; because it says "if it wants to make a teleport ending at their planet", that suggests that each time you make a teleport that ends there, you pay. But it's ambiguous. However, typical graph problems of connecting components at minimum cost where each node has a cost to be "chosen" as a hub and you can connect chosen nodes for free: That is like building a Steiner tree or connecting components via adding edges with cost = sum of endpoint costs? Actually there's known problem: "Given a graph with nodes having weights, you can add an edge between any two nodes with cost equal to sum of their weights, find min cost to make graph connected." This is similar to connecting components by adding edges between any two nodes, where edge cost = C_u + C_v. This reduces to: For each component, we can pick a node with minimum C_i, and to connect all components, we need to add edges connecting them, like building a spanning tree over components, where cost of connecting component i and j is min_{u in comp i, v in comp j} (C_u + C_v). This is like: the cheapest edge between two components is the sum of the minimum costs in each component, because you would pick the cheapest node from each component. So the minimal cost to connect all components into one connected graph is: sum over all components of min cost in component? Actually, if we have k components, we need to add at least k-1 edges to connect them. A minimum spanning tree over components with edge cost defined as min_{u in comp i, v in comp j} (C_u + C_v) yields minimal total cost. But note that edge cost = min_{u in comp i} C_u + min_{v in comp j} C_v? Is it always optimal to pick the minimum node from each component for each connection? Since for connecting two components, the cheapest possible edge between them indeed is (min in comp i) + (min in comp j), because any edge from a node in i to a node in j costs sum of their costs, so the minimum sum is achieved by taking the minimum in each component. So the cost to connect two components i and j is m_i + m_j, where m_i = min_{v in comp i} C_v.
Then to connect all components, we need to select a set of connections forming a tree. If we have components with minimum values m1, m2, ..., mk, then the minimal cost to interconnect them is something like: connect all components to the component with the smallest m? Actually, the MST on a complete graph with edge weights m_i + m_j. For such a graph, the MST can be formed by connecting each component (except the one with smallest m) to the component with the smallest m. Because for any two components i and j, weight = m_i+m_j. If we sort m_i ascending: m1 <= m2 <= ... <= mk. Then the total cost of connecting all to m1 is: sum_{i=2..k} (m1 + m_i) = (k-1)m1 + sum_{i=2..k} m_i. Alternatively, if we consider a star centered at component with smallest m, that's a tree. Could there be a cheaper tree? Consider three components with m1=1, m2=2, m3=3. Star at m1: cost = (1+2)+(1+3)=7. Alternative tree m1-m2 (1+2=3) and m2-m3 (2+3=5) total=8. So star is cheaper. In general, the MST for such a complete graph with edge weight m_i+m_j is to take the smallest m as hub and connect all others to it. Because any edge weight is sum of two mins, and to connect all nodes, we need to include all m_i at least once. The total cost of any tree = sum_{edges} (m_u + m_v) = for each node, its m multiplied by (degree in tree). Since sum of degrees = 2(k-1), total = sum_{i} m_i * degree_i. To minimize this, we want to assign higher degrees to nodes with smaller m. The optimal is to give the smallest m the degree (k-1) and all others degree 1. That yields total = m1*(k-1) + sum_{i=2..k} m_i*1 = (k-1)*m1 + sum_{i=2..k} m_i. That matches the star. So MST cost = sum_{i=1..k} m_i + (k-2)*m1? Let's compute: (k-1)*m1 + sum_{i=2..k} m_i = sum_{i=1..k} m_i + (k-2)*m1? Because sum_{i=1..k} m_i = m1 + sum_{i=2..k} m_i, then adding (k-1)*m1 gives? Actually (k-1)*m1 + sum_{i=2..k} m_i = (m1 + (k-2)*m1) + sum_{i=2..k} m_i = sum_{i=1..k} m_i + (k-2)*m1. Yes. So MST cost = sum_{i=1..k} m_i + (k-2)*m_min.
Alternatively, we can think: we need to connect components; we must select some nodes to be "ports" for teleports. But if we add a teleport between two planets, both planets become "used" for teleport. If we could reuse planets, maybe we can have multiple teleports from the same planet; but each teleport endpoint incurs cost per teleport? Let's examine sample: If cost were per planet (one-time) then adding a teleport between 1 and 4 would incur cost C1 + C4 = 3. That's fine. If we added two teleports, say 1-4 and 1-5, if cost per teleport endpoint, then for first teleport: pay C1, C4; second: pay C1 again? That would be double counted. Would that be realistic? Not sure. However, typical problems with node costs and adding edges often treat the node cost as a one-time activation cost: you pay to "upgrade" a node, and then you can connect upgraded nodes for free or at some edge cost. But here they explicitly say "if it wants to make a teleport ending at their planet". This could be interpreted as each teleport that ends at a planet incurs a tax. So if you have multiple teleports from the same planet, you pay tax multiple times. Which one yields the sample answer? Let's test: If cost per teleport endpoint, then connecting two components with a single teleport costs C_u + C_v. That's what we used. If we needed to connect three components, maybe we could do two teleports: if we connect component A to B using nodes a (cost C_a) and b (C_b), and then connect B to C using nodes b' (maybe same node b or different) and c, then total cost = C_a + C_b + C_{b'} + C_c. If we could reuse b (i.e., same node used for both teleports), would we pay C_b twice? If per teleport, yes, you pay each time you make a teleport ending at b. So using the same node twice doubles its cost. If per planet (one-time), you would pay C_b only once. So the optimal strategy may differ. In many similar problems, the optimal solution is to choose one node in each component with minimal cost, and then connect them via a star centered at the globally minimal node (pay that node's cost multiple times? If per teleport, each edge uses its endpoints, so the hub node would be used in (k-1) edges, thus incurring its cost (k-1) times. That would yield total cost = (k-1)m_min + sum_{i=2..k} m_i? Actually if we use the same node as hub for all connections, we would pay its cost for each teleport (since each teleport ends at that node). So total cost = (k-1)(m_min) (for hub) + sum_{i=2..k} m_i (for the other endpoints). That's exactly the same as before! But if cost per planet is one-time, then the hub cost would be counted only once, so total = m_min + sum_{i=2..k} m_i = sum m_i, which is smaller. But which is correct? Sample 1 has k=2 components, so (k-2)*m_min = 0, both formulas give sum m_i = m1+m2. m1 for component {1,2,3} min is 1; for {4,5,6} min is 2; sum = 3, matches answer. For k=2, both per-teleport and per-planet give the same because hub is used once (only one edge). So sample doesn't differentiate.
Let's examine sample 2:
Input:
3 1
2 3
1
-1
-1
So N=3, M=1 edge: (2,3). So components: component1: {2,3} connected; component2: {1} isolated. Costs: planet1: 1 (positive); planet2: -1 (negative, type2); planet3: -1 (negative). The GFA wants to connect all planets. We can add teleports. According to the description, type2 governments (negative C) are to be avoided. But the problem statement says: "The GFA would always avoid such governments no matter what the consequences are, because these kind of governments have always some dirty plans in their minds for the GFA." That suggests they would never make a teleport ending at a type2 planet. So maybe we are not allowed to use planets with negative C as teleport endpoints. If so, then the only possible teleport endpoints are planet1 with cost 1. But we need to connect component2 (planet1) to component1 (planets 2,3). If we cannot use planets 2 or 3 as endpoints, we cannot add a teleport to them. However, we could perhaps add a teleport between planet1 and some planet in component1, but that would involve planet2 or 3 as endpoint, which are type2 and thus forbidden. Then it's impossible, output -1. That matches sample output -1.
But what if we ignore the "avoid" statement and treat negative costs as just negative (i.e., we get money), then we could connect planet1 to either planet2 or planet3. The cheapest: connect 1 (cost 1) and 2 (cost -1): total 0. Or 1 and 3: total 0. So minimum cost would be 0 (or maybe even negative? but they want to spend as little money as possible, so negative would be a profit, but they want to minimize spending, so negative is less than 0, but they might want to accept negative? Usually, minimization of cost would prefer negative, but the statement says they avoid such governments no matter what. So we must not use them. So answer -1.)
But is there any nuance? Could it be that the GFA is forced to avoid type2 governments meaning they would not accept money from them, but they might still use them if they have to, but they'd have to pay them? No, it says they want to avoid such governments. It could be interpreted as they will never make a teleport ending at such planets. So they are not allowed to use them as teleport endpoints.
Thus constraints: For each planet i, if C_i >= 0, we can use it as endpoint but must pay C_i per teleport that ends there (or per usage?). If C_i < 0, we are not allowed to use it as endpoint at all. (Note: the statement says "The GFA would always avoid such governments no matter what the consequences are", implying they will not engage with them; so using a teleport there is engaging, so prohibited.)
Therefore, we must only use planets with non-negative C as teleport endpoints. However, we can still use the existing spaceways to travel through all planets regardless of type. So connectivity via spaceways includes all nodes. But teleports can only be placed between allowed nodes (C >= 0). That is crucial.
Now we need to make the whole graph (all N planets) connected by adding teleport edges (bidirectional) between allowed nodes (i.e., nodes with C >= 0). The teleport edges can be added arbitrarily between any two allowed nodes, even if they are in the same component, but we only need to ensure overall connectivity. Adding extra edges is unnecessary and would increase cost. So we need to find minimum cost to connect all components (connected components of the original graph) using teleports that connect allowed nodes. But teleports can only be placed on allowed nodes. However, even if a component contains no allowed nodes (i.e., all its nodes have C < 0), then we cannot attach a teleport to that component because any teleport endpoint inside that component would be disallowed. That would make it impossible to connect that component to the rest. Unless that component is already connected to others via spaceways? But by definition, components are separate; if a component has no allowed nodes, we cannot add any teleport that touches it, so it remains isolated. So answer -1.
Similarly, if there is exactly one component overall, no teleports needed, cost 0.
General approach: Compute connected components of the given graph (using DSU or DFS). For each component, we need to know whether it has at least one allowed node (C >= 0). If any component has none, answer -1.
Otherwise, we can connect components using teleports. Teleports are added between allowed nodes. For each component, we can choose one allowed node (maybe the one with minimum C) to be the "port" for that component. Because any teleport connecting this component to another must use an allowed node from each component. If we use a node with higher C, it would increase cost. So for component i, let min_cost_i = minimum C among nodes with C >= 0 in that component. We'll call these "port nodes".
Now we need to add edges between components to make them all connected. Each added teleport will connect two allowed nodes, one from component i and one from component j, costing C_u + C_v. The cheapest edge between i and j is min_cost_i + min_cost_j, achieved by picking the min-cost allowed node in each component.
Thus we need to find the minimum cost to connect all components (with these min costs) using edges with weight equal to sum of the component mins.
But is it always optimal to use exactly one node per component? Could we ever use a node that is not the minimum in its component for some connection, to reduce total cost due to multiple connections from the same component? For instance, if a component must be connected to multiple other components, then using the same min node for all connections will incur its cost multiple times (if cost per teleport endpoint). But if we could use different nodes from the same component for different connections, maybe we can reduce total cost if there is a node with slightly higher cost but we can spread connections? However, the per-teleport cost for each endpoint is incurred each time we use that node. So if a component has to serve as hub for multiple edges, using the same cheap node multiple times costs that cheap node's cost multiplied by its degree. Alternatively, we could use different nodes: suppose component has two allowed nodes with costs a (min) and b (second min). If we need to connect to two other components, we could use a for both edges: cost = 2a + other endpoints. Or use a for one and b for the other: cost = a + b + other endpoints. Which is better? Since a <= b, 2a <= a + b? Actually 2a <= a+b implies a <= b, which is true. So using the same cheapest node twice is cheaper or equal than using two different nodes. So it's always better to reuse the cheapest node for all connections from that component, if cost per usage.
What if we have to connect the component to many others, and the cheapest node's cost is high relative to others? Actually the cheapest is the smallest, so reusing it yields the smallest total contribution from that component. So indeed, each component's total contribution to the overall cost is min_cost_i * (degree_i) where degree_i is number of teleports incident to that component in the final tree (each component is a supernode). To minimize sum_{edges} (min_i + min_j) = sum_i min_i * degree_i, we want to assign higher degrees to components with smaller min_i. This is exactly the MST problem on complete graph with node weights min_i, where edge weight = min_i + min_j. As argued, the optimal tree is a star centered at the component with the smallest min_i. But careful: In the MST, each component's degree in the tree will be determined by its position; the star gives degree (k-1) to the smallest min component, and degree 1 to all others. This yields total cost = (k-1)*m_min + sum_{i != min} m_i = sum_i m_i + (k-2)*m_min. This is optimal.
But is there any possibility to avoid paying the cost for the hub component multiple times by not using teleports at all for some connections? We only have spaceways (original edges) that already connect nodes within each component. So we must connect components using teleports. So we need at least k-1 teleports, each connecting two components.
Thus the minimal cost appears to be sum_{i=1..k} m_i + (k-2) * m_min, where m_min is the smallest m_i among all components. However, we need to verify that this holds when some components have only one allowed node? That's fine.
But we should double-check the scenario where a component may have more than one allowed node, but the cheapest node might be used also as an endpoint for a teleport that connects within the same component? That would be pointless because within a component it's already connected. So no.
Also, could we ever benefit from adding extra teleports within a component to perhaps "bypass" using the cheapest node? Unlikely; adding extra edges never reduces the number of required inter-component edges.
Thus the answer seems to be: if all components have at least one allowed node, then compute m_i = min{C_j >= 0 for j in component i}. Sort them. Let k = number of components. If k == 1, answer 0. Else, let smallest = m_min. Total = (k-2)*smallest + sum of all m_i.
But wait: There is a nuance: The teleport cost might be per teleport, and we might be allowed to use multiple teleports from the same component to different components, but what about connecting components indirectly? In a tree, each component is a node. The MST approach is standard. However, we must be careful: The edge cost between components i and j is not exactly m_i + m_j? Because we need to pick two specific nodes, one from each component, and we pay C_u for using u as endpoint of that teleport, and C_v for v. If we have already used node u in a previous teleport, do we pay C_u again? According to per-teleport interpretation, yes. So in a tree, each edge incident to component i will correspond to a teleport whose endpoint in component i is some node (maybe the same node for multiple edges). The total cost contribution from component i is sum over edges incident to i of C_{node_used_for_that_edge}. If we always choose the cheapest node for all edges, that sum is m_i * degree_i. That's consistent.
Now is it always possible to realize a tree where a component i uses the same node for all its incident teleports? Since teleports are edges between specific nodes. If we have component i with node x (the cheapest) and we want to connect it to component j using teleport (x, y_j) where y_j is the cheapest node in component j. That's fine. But what if component i is connected to multiple components j1, j2, ...? We would need multiple teleports, all with endpoint x. That's allowed; we can have multiple teleports from the same planet. So it's feasible.
Now consider if the cheapest node in a component is not reachable from other nodes? Actually within a component, all nodes are connected via spaceways, so we can travel to that node. So we can place teleports there.
Thus the MST star is realizable.
But there is a twist: The statement "The GFA would always avoid such governments no matter what the consequences are" might mean that they avoid type2 governments, i.e., they will not accept their money, but perhaps they still can use them if they pay them? Actually, type2 governments give money to GFA (sponsor), but GFA wants to avoid them because they have dirty plans. So they would not want to engage with them at all. So they would not make a teleport ending at those planets even if it would bring them money. But could they still use them as intermediate nodes for travel via spaceways? Yes, because spaceways are already there, they don't involve any new agreement. So they can travel through type2 planets using existing spaceways. That's fine.
Thus the restriction: Only nodes with C >= 0 can be used as teleport endpoints. So for a component with all C < 0, it's impossible to attach a teleport, so it remains isolated. Therefore answer -1.
Now, what about nodes with C = 0? They are type1 (non-negative) but tax is 0, so no cost.
Edge cases: N up to 100,000, M up to 1,000,000. So we need efficient algorithm.
We also have to compute components, find min C among nodes with C>=0 for each component, check if any component has none. If there is exactly one component, answer 0.
If there are multiple components, compute total = sum(m_i) + (k-2) * min_m.
But is that always the minimal? Let's test with simple cases:
Case: 3 components, m = [5, 5, 5]. Then formula gives sum=15 + (3-2)*5 = 20? Wait: sum m_i = 5+5+5=15, (k-2)min = 15=5, total=20. But star: connect all to smallest (5) yields edges: 5+5 (to second) =10, plus 5+5 (to third) =10, total 20. Alternatively, a chain: 5+5=10 and 5+5=10 => 20. So consistent.
Case: m = [1, 100, 100]. k=3. sum=201, + (1)*1=202? Actually sum m_i = 1+100+100=201, (k-2)=1, *min=1 => total=202. Star: edges: 1+100=101, 1+100=101 =>202. Chain: connect 1-100 (101) and 100-100 (200) =>301. So star is optimal.
Case: m = [2,3,6,7]. k=4. sum=18, + (2)*2=22. Star: 2+3=5, 2+6=8, 2+7=9 =>22. MST alternative? Connect 2-3 (5), 2-6 (8), 2-7 (9) same. If we connect 2-3 (5), 3-6 (9), 3-7 (10) =>24. So formula works.
Thus answer is as described.
Now, but what about the possibility of not using the minimal node in some component because that component might have a node with C < 0 that we could use? Not allowed. So no.
Thus solution seems straightforward.
But wait: There is another nuance: Could we add a teleport between two nodes in the same component? That could create a new path, but doesn't help connect different components. So not needed.
Thus answer seems to be: if there exists a connected component with no non-negative C node, output -1. Else if number of components == 1, output 0. Else output (sum of min_nonneg_C over components) + (num_components - 2) * (global_min_nonneg_C).
Check sample1: components: comp1 min=1, comp2 min=2, k=2, sum=3, (k-2)=0 =>3. OK.
Sample2: components: comp1 (nodes 2,3) has both C negative, so no allowed node => -1. OK.
Now consider other cases:
-
If there is at least one component with allowed node, but the global graph has only one component? Then answer 0. Good.
-
If k>1, we must ensure that each component has at least one allowed node. So answer computed.
Now, are there any scenarios where we might need to pay cost even if there is only one component? Possibly not.
But wait: The statement: "The GFA wants to make bi-directional teleports between planets such that the football teams of any planet can reach any other planet to play a football match, using spaceways between the planets and/or teleports made by the GFA." So if the graph is already connected, no teleports needed, cost 0.
Thus algorithm:
- Read N, M.
- Build adjacency list or just use DSU to compute connected components.
Since M up to 1e6, N up to 1e5, DSU is fine. We'll use union find.
- For each edge (A, B), union(A, B).
- Read array C[1..N].
- For each node i, if C[i] >= 0, then for its component (root), we track:
- if not yet set min_cost[root] or C[i] < min_cost[root], update.
- also mark that component has at least one non-negative node.
- After processing all nodes, iterate over all components (roots). Count number of components. For each root, if no non-negative node found, then impossible -> print -1 and exit.
- Let k = number of distinct roots (components). If k == 1, print 0.
- Else, gather all min_cost values into a list mins.
Find global_min = min(mins).
Compute total = sum(mins) + (k-2) * global_min.
Print total.
But careful: Are we sure that the cost of a teleport is sum of the endpoint costs, and we incur cost for each teleport? Yes, as per sample and reasoning.
Now, we need to consider the possibility that we might not need to use the min node in each component if we can connect components via a chain where a component's min is not used because we might connect through some other node? For example, suppose component A has min = 5, but also has a node with cost 6. Component B has min = 10. We want to connect A to B. Using node with cost 6 from A and min 10 from B costs 16, while using min 5 gives 15. So min is always better for a single connection. For multiple connections, using min for all edges is optimal as argued.
Thus the solution seems correct.
But wait: There's nuance: The GFA wants to spend as little money as possible. If we have type2 governments (C<0) we avoid them, but perhaps the phrase "always avoid such governments no matter what the consequences are" could mean they will not accept their money, but they might still be forced to use them if necessary? But sample2 says -1, meaning impossible. That indicates they cannot connect if it requires using them. So it's not forced; they would rather fail than use them. So the plan is impossible if any component lacks a non-negative node.
But what if there is a component with all negative but it's already connected to others via spaceways? That can't happen because components are defined by spaceways; if it's all negative but has an edge to a component with non-negative, they'd be in same component. So the condition stands: if a component has any negative nodes only, it's isolated and impossible.
Now, think about the case where some components have only one node with non-negative, but that node might be used for multiple teleports. That's okay.
Now, complexity: O(N + M * α(N)). DSU union operations.
Now, is there any catch regarding large input/output? They warn about fast I/O. Use sys.stdin.buffer, sys.stdout.write.
Now, let's test with some custom cases:
Case: N=2, M=0, C1=5, C2=10. Two isolated nodes, both allowed. k=2, mins = [5,10], global_min=5, total = 5+10 + (2-2)*5 = 15. But we only need one teleport between them. The cheapest teleport is between node1 and node2 costing 5+10=15. Yes.
Case: N=3, M=0, all allowed: C=[1,2,3]. 3 isolated nodes => k=3. mins = [1,2,3], global_min=1, total = 1+2+3 + (3-2)*1 =6+1=7? Wait sum=6, (k-2)=1, *1=1 => total=7. Check: We need to connect three nodes. Options: Star at node1: edges 1-2 (3), 1-3 (4) total 7. Chain: 1-2 (3), 2-3 (5) total 8. So 7 is min. So formula correct.
Case: N=3, M=0, but one node has C=0, others positive: [0,5,5]. k=3, mins=[0,5,5], global_min=0, total = 10 + (1)*0 =10. Star at 0: edges 0+5=5, 0+5=5 =>10. Good.
Case: N=3, M=0, one node allowed, others negative? Actually if any component has no allowed, answer -1. But consider component: each node isolated, two nodes negative, one positive. Then we have three components? Wait M=0, so each node is separate component. The component containing negative nodes each are separate components. Those components have no allowed node because C<0 (negative). So they are impossible to connect, because we cannot attach a teleport to them. So answer -1. Indeed, you need to connect the negative nodes too, but you cannot. So -1.
Thus condition: every component must have at least one non-negative node. That means if there is any node with C<0 and no edge to any non-negative node (i.e., it's isolated or in a component consisting only of negative nodes), then it's impossible. So if negative nodes are only present in components that also contain at least one non-negative node, it's okay; they can be reached via spaceways.
Now, consider scenario: a component has both negative and non-negative nodes. The min non-negative is some value. That's fine.
Now, check if we need to consider that using a teleport might also allow travel through negative nodes? No, we are only connecting components via teleports, the internal connectivity via spaceways already includes negative nodes.
Now, is there any scenario where we could connect two components by using a teleport that ends at a negative node, but we avoid it? No, because we avoid them, so not allowed. So we stick to non-negative.
Now, what about C=0? That is non-negative, type1, but tax is zero, so it's allowed and no cost.
Now, double-check the phrase: "If C ≥ 0, then it represents the tax value which the GFA has to pay to the government of planet i (it's a type 1 government). If C < 0, then it represents the money the ith government will pay to the GFA (it's a type 2 government)." So C negative means they would pay money (sponsorship). But the GFA avoids them. So we treat C<0 as disallowed endpoints.
Thus solution stands.
But wait: Could there be a scenario where the minimal cost is negative? Possibly if we were allowed to use negative nodes, then answer could be negative. But since we are not allowed, we avoid them.
Now, verify the reasoning with the "avoid" statement: It says "The GFA would always avoid such governments no matter what the consequences are". That implies they will never make a teleport ending at those planets. So it's a constraint.
Now, edge case: If there are no allowed nodes at all (all C < 0) but the graph is already connected? Then k=1 (since all nodes are connected via spaceways). In that case, no teleports needed, so cost 0? But would it be allowed? The requirement is to have connectivity using spaceways and/or teleports. If the graph is already connected via spaceways, then we don't need teleports. The GFA doesn't need to interact with any government if no teleports are made. So answer should be 0, because they can just rely on existing spaceways. The "avoid" only applies if they make a teleport ending at such planets. So if the graph is already connected, they don't need to make any teleport, so they don't need to engage with type2 governments. So answer 0. But does the problem say they want to make teleports? "Now, the GFA wants to make bi-directional teleports between planets such that ... using spaceways and/or teleports". It doesn't say they must make at least one; they can make zero if already connected. So indeed if already connected, answer 0. That's consistent with our condition: if k==1, answer 0. And that holds even if all C<0 because we don't need teleports.
But if k>1 and all C<0, then some component has no allowed node? Actually, all nodes are negative, so each component has no allowed node (since allowed defined as C>=0). Then our condition would say impossible, output -1. But is there a way to connect components without teleports? No, because they are separate components, need teleports. Teleports require endpoints, which would have to be on some nodes. But all nodes are negative, which are forbidden. So indeed impossible -> -1. That matches intuition: if there are multiple components and all nodes are type2, GFA cannot connect them without engaging with type2 governments, which they avoid. So answer -1.
Thus our approach covers that.
Now, is there any scenario where we could connect components using a teleport that ends at a non-negative node in one component and ... the other component has only negative nodes, so can't attach. So impossible.
Now, check if there is any possibility to use multiple teleports to "bridge" through an intermediate component that has non-negative nodes, but the target component has only negative nodes? Suppose component A has non-negative, component B has only negative, component C has non-negative. Could we connect B to A via a teleport? No, because teleport would need an endpoint in B, which is negative -> forbidden. So B remains isolated. So impossible.
Thus condition.
Now, we need to implement DSU with path compression and union by rank.
Now, one more nuance: Could we have a teleport between two nodes in the same component that are both negative? That wouldn't help connectivity across components and would be pointless. So not needed.
Thus algorithm is simple.
But wait: Could there be an alternative approach that uses multiple teleports to reduce cost? For example, if we have three components with mins 10, 20, 100. The star centered at 10 yields cost = (10+20)+(10+100)=140. Could we do: connect 10-20 (30), then from 20 connect to 100 (120) total 150, worse. But what about using a different node from the component with min=20? If component with min=20 also has another node cost 25, we could use 10-20 (30) and then 25-100 (125) total 155. So star is best.
Thus formula stands.
Now, verify with k=2: total = sum(m_i) (since (k-2)=0). That's consistent with adding one edge between the two min nodes.
Thus solution is clear.
Now, is there any scenario where we could avoid paying the cost for a component by not using it as an endpoint at all? For example, if we have three components, we could connect them in a chain. The middle component will have degree 2, so its cost is paid twice. But if that component's min is high, we might want to give it degree 1. In the star, the component with the smallest min gets degree k-1. Since its min is smallest, it's okay. So overall minimal.
Now, note: If there are multiple components with the same minimal min, the star can be centered at any; the cost is the same.
Now, need to be careful: The total sum of mins plus (k-2)*global_min can be computed without sorting if we know sum and min. But we need to know the number of components and the sum of mins and global min.
Implementation steps:
-
Initialize DSU for N.
-
For each edge (a,b): union(a-1,b-1) (0-index).
-
Read array C of size N.
-
Create arrays: comp_min initialized to INF (maybe a large number) or -1 to indicate no non-negative yet. Also boolean hasNonNeg set false.
-
Iterate i from 0 to N-1:
root = find(i)
if C[i] >= 0:
hasNonNeg[root] = True? Actually we need to store min.
if comp_min[root] is sentinel or C[i] < comp_min[root]: comp_min[root] = C[i].
else:
// negative, ignore for min, but we still have a component; we need to know that component exists.
-
After loop, we need to gather roots. For each root (unique), check if comp_min[root] is defined (i.e., has at least one non-negative). If not, output -1.
-
Count number of components k = number of roots where comp_min is defined? But careful: A component might have no non-negative node; we already output -1. So after checking, we can proceed with only those components that have non-negative, but wait: components that have no non-negative are impossible, so we return -1. So we don't need to count them separately; just if any component has no non-negative, answer -1.
-
So after verifying all components have at least one non-negative, we have k = number of components (the total number of distinct roots, which should be same as number of components). Because all components have at least one non-negative, so they are all valid.
-
Then compute sum_mins = sum(comp_min[root] for each root) and global_min = min(comp_min[root]).
-
If k == 1: answer 0
-
Else answer = sum_mins + (k - 2) * global_min.
Now, double-check that comp_min is defined for every component. In the loop, we only set comp_min when encountering a non-negative node. For components that only have negative nodes, comp_min remains undefined (or sentinel). So we detect that and output -1.
Now, potential pitfalls:
-
N up to 100k, M up to 1e6, so reading input efficiently is important. Use sys.stdin.buffer.read() and parse ints.
-
DSU with 1e5 nodes is fine.
-
Edge list may have self-loops? Input says A ≠ B, so none.
-
The graph may have multiple edges? Possibly, but DSU handles duplicates.
Now, consider scenario where there is a component with all nodes negative but it's already connected to another component via spaceways? That contradicts definition of component. So no.
Now, what about the scenario where a component has all nodes negative, but the whole graph is connected? Then that component is the whole graph, so there are no other components. Then k=1, we output 0. That is fine: all nodes are type2, but the graph is already connected, so no teleports needed. So it's possible.
But wait: "The GFA would always avoid such governments no matter what the consequences are". If the graph is already connected, they don't need to interact. So answer 0. That seems plausible.
Now, I'd like to test some more cases mentally.
Case: N=4, M=2 edges: 1-2, 3-4. So two components: {1,2}, {3,4}. Costs: 1:5, 2:7, 3: -1, 4: -1. Component2 has no allowed node, so impossible -> -1.
Case: N=4, M=2 edges: 1-2, 3-4. Costs: 1:5, 2:5, 3: 0, 4: 10. Both components have allowed nodes (comp1 min=5, comp2 min=0). k=2 => total = 5+0=5. Teleport between min nodes: 5 and 0 cost 5. Works.
Case: N=4, M=0 (all isolated). Costs: all positive: [1,2,3,4]. Four components, mins = [1,2,3,4], global_min=1, sum=10, (4-2)=2 => total=10+2=12. Let's verify: Star at 1: edges: 1-2=3, 1-3=4, 1-4=5 => total 12. Good.
Case: N=4, M=0, Costs: [0,0,0,0]. mins all 0, sum=0, (4-2)*0=0 => total 0. So no cost, we can add teleports with zero cost? But teleport endpoints cost 0 each, so adding edges costs 0, so they can connect all for free. So answer 0. Indeed minimal cost 0.
Case: N=4, M=0, Costs: [0, 10, 10, 10]. mins [0,10,10,10], sum=30, (4-2)0=0 => total 30. Star at 0: edges 0+10 each =103=30. Good.
Now, what if there are many components, say 100k, we need to compute sum and min efficiently. That's O(N).
Now, we need to be careful about integer sizes: C up to 10,000, N up to 100k, sum may be up to 1e9, plus (k-2)*min also up to ~1e9, so 32-bit int may be borderline but safe if using 64-bit (Python int is arbitrary). So fine.
Now, check if there is any scenario where we might not need to connect all components directly? The goal is that any planet can reach any other, so the graph must be connected. So we need to make it connected.
Now, let's double-check the interpretation of teleport cost: Could it be that we pay the tax only once per planet, regardless of number of teleports? Let's test with a scenario where k=3, mins [1,2,3]. If per-planet one-time, then we could choose to "activate" planets 1,2,3 (pay 1+2+3=6) and then connect them with teleports for free? But the problem says "make a teleport ending at their planet". If tax is per teleport, then to connect all three, we need at least two teleports. If we activate planets once, then we could add teleports between them without extra cost. That would be total cost = sum of activation costs = 6. But with per-teleport, total cost is 7. Which one is more plausible? Sample1: two components, sum mins = 3. If per-planet one-time, cost would be 1+2=3, same as per-teleport. So not distinguishable. Let's try a case where k=3 with mins [1,100,100]. Per-teleport: 1+100+100 + (3-2)*1 = 202. Per-planet: we would need to activate three planets: 1+100+100 = 201, and then we need to connect them; perhaps we need to add edges? If after activation, teleports are free, we could add two edges connecting them: cost 0 after activation? Then total 201. But is that allowed? The problem says: "if it wants to make a teleport ending at their planet, it has to pay the tax." That could be interpreted as each time you make a teleport, you pay tax to the endpoint's government. So it's per teleport, not per planet. Usually in such problems, if you build an airport at a city, you pay cost to build the airport, and then you can add flights between airports for free or some cost. Here, they are building teleports, which are like direct connections; each teleport is a new infrastructure. The tax is incurred per teleport, not per planet. The phrasing "if it wants to make a teleport ending at their planet" suggests that for each teleport that ends there, they have to pay. So it's per teleport endpoint. That leads to the cost we used.
Could we conceive a scenario where it's per planet? Then the problem reduces to: we need to select a set of planets to become "hubs" (teleport endpoints) such that by adding teleports between them (presumably with no additional cost) we can connect all components. But we also need to ensure that each component has at least one hub, and then we can connect hubs with teleports. But would teleports themselves have cost? If there is no cost for the teleport beyond the endpoint taxes, then connecting any two hubs would cost nothing extra. So we could just select one hub per component, and then connect them arbitrarily (forming a tree) without extra cost. Then total cost would be sum of selected hub costs. To minimize, we would choose the minimum cost node in each component, and that's it. So total = sum(m_i). That would be different from our formula when k>2. For k=3, sum(m_i) vs sum(m_i)+(k-2)*min. In the [1,100,100] example, sum=201 vs 202. So difference 1. Which is correct? The problem might be known. Let's search memory: This problem might be from some contest (Galactik Football) – I recall a problem named "Galactik Football" from CodeChef maybe? Actually there is a problem "Galactik Football" on CodeChef. I think I've seen it. I recall a problem about connecting components with minimum cost where each node has a cost, and you can add edges between any two nodes at cost equal to the sum of their costs. And the solution was to take the minimum from each component and then connect them with a star centered at the global minimum. That's exactly what we have. Let me recall: There's a CodeChef problem "GALACTIK" maybe? I'm not entirely sure but I've seen something similar. Also there is a known problem "Galactik Football" on SPOJ? Actually, I recall a problem about connecting components with teleports and each planet has a tax; solution uses DSU and min costs. I think it's indeed the sum plus (k-2)*min. So per-teleport interpretation is standard.
But we need to confirm with a more complex example if the problem statement might hint at per teleport. Let's read again: "Some of the governments are greedy ... So each of these government has asked the GFA for a tax value which it has to pay if it wants to make a teleport ending at their planet." This implies that for each teleport they make that ends at that planet, they have to pay the tax. It doesn't say it's a one-time fee for using the planet as an endpoint. So it's per teleport. So if they make multiple teleports ending at the same planet, they pay multiple times.
Also, the phrase "Others want to sponsor the event, so they will give money to the GFA if they make a teleport ending at their planet". Again, per teleport, they would receive money. But they avoid these.
Thus per teleport is correct.
Thus our formula stands.
Now, edge case: What if global_min is from a component that is the only component? Not relevant.
Now, we should also consider that we could possibly avoid using the global_min component as hub and use a different component if it has the same min? But it's same cost.
Now, check if there is any scenario where we could get a cheaper solution by adding extra teleports that connect more than the minimum needed (i.e., a cycle) to somehow reduce cost? Adding extra edges would only increase cost because each edge adds positive cost (since costs are non-negative for allowed nodes). So not beneficial.
Now, one more nuance: What if some allowed node has cost 0? That's fine.
Now, we should consider if there is a possibility to not use a teleport at all for some component if that component is connected via a chain of other components through spaceways? But we are connecting components, so we need to merge them.
Thus solution is sound.
Now, we need to implement efficiently.
Implementation details:
- Use sys.stdin.buffer.read() to read all input, split into integers.
- N, M = first two ints.
- Then 2*M ints for edges.
- Then N ints for costs.
DSU:
parent = list(range(N))
rank = [0]*N
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
Or recursive with path compression.
Union:
def union(a,b):
ra = find(a); rb = find(b)
if ra == rb: return
if rank[ra] < rank[rb]:
parent[ra] = rb
elif rank[ra] > rank[rb]:
parent[rb] = ra
else:
parent[rb] = ra
rank[ra] += 1
After processing all edges, we compress all finds perhaps by calling find(i) for each i to get final roots.
Now, we need arrays for component data. Since N up to 100k, we can allocate arrays of size N for min_cost and maybe a boolean flag. We'll initialize min_cost with a large sentinel (e.g., INF = 10**9+5, or None). But we also need to know which roots exist. We can maintain a dictionary mapping root to index, but simpler: after DSU, we can iterate over all nodes, find root, and update per root data using arrays indexed by root (which is 0..N-1). But root values are not contiguous; we can later collect by scanning all nodes and storing data in arrays root_min[root] and root_has[root] (boolean). Then we need to collect distinct roots: we can have a set or simply iterate over nodes and if root == i (i is its own parent) then it's a root. However, after path compression, many nodes may not be roots. But we can still iterate i from 0 to N-1 and if parent[i]==i (or find(i)==i) then it's a root. However, with path compression, after calling find on all nodes, the parent array should be updated such that each node points directly to its root. So we can then iterate and check if parent[i]==i. That gives all roots. But we need to ensure that we have called find on each node to compress paths. Typically we can just call find(i) for each i when processing costs to get root, and also record data.
Better approach: For each node i:
r = find(i) # ensure compression
if C[i] >= 0:
if min_cost[r] is None or C[i] < min_cost[r]:
min_cost[r] = C[i]
# negative ignored
But we also need to know for each component whether there is any non-negative node. Since we only set min_cost when we encounter non-negative, we can treat min_cost[r] as None if none. After processing all nodes, we iterate over all roots (where parent[i]==i). For each root, if min_cost[root] is None -> component has no non-negative -> print -1.
But careful: Some root may not have been visited in the loop? Actually we are iterating all nodes, so each component's root will be encountered as the root for its nodes. So min_cost for that root will be set if any node has C>=0; otherwise remain None.
Thus after loop, we can collect roots where parent[i]==i. For each such i, if min_cost[i] is None: print -1 and exit.
If all have min_cost, then compute k = number of roots, sum_mins = sum(min_cost[i] for i in roots), global_min = min(min_cost[i] for i in roots). Then if k==1: print 0 else print sum_mins + (k-2)*global_min.
Potential issues:
- Some roots may have been merged but still have parent[i]==i? Actually after unions, parent array is consistent. For each node, we should call find(i) to compress when reading costs. That ensures all nodes point to root. Then we can iterate i from 0 to N-1 and if parent[i]==i, it's a root. But note that after compression, some roots may not have parent[i]==i? Actually root nodes will have parent[i]==i. Others will have parent[i]!=i. So counting roots by checking parent[i]==i is valid.
But we need to be careful: When we call find(i) during cost processing, we may compress paths, but the root's parent may still be itself. So that's fine.
Thus algorithm is O(N + M * α(N)). Should fit.
Now, we should also handle the case where N=0? Not possible, N>=1.
Now, test with given samples.
Sample 1:
N=6, M=6, edges: unions result in two components: {1,2,3} and {4,5,6}. Costs: 1,3,5,2,4,6 all non-negative. mins: comp1=1, comp2=2. k=2, sum=3, (2-2)=0 =>3.
Sample 2:
N=3, M=1: edge 2-3. DSU: 2 and 3 same component; 1 separate. Costs: 1 (>=0), -1, -1. For component of 1: min=1. For component of 2,3: no non-negative => min None. So print -1.
Matches.
Now, test a case where k=1 and some negative nodes: N=3, M=2 edges: 1-2, 2-3, so whole graph connected. Costs: -1,-2,-3. All negative. All nodes in one component. For the root (say 1), we process nodes: all negative, so min_cost[root] remains None. After loop, we find root with min_cost None? Then we would output -1 according to our check? But that would be wrong because the graph is already connected; we don't need teleports, so answer should be 0. Our condition says if any component has no non-negative node, output -1. But this component has no non-negative node; but since it's the only component, we don't need teleports. However, do we need to consider that if a component has no non-negative nodes but it's the only component, we don't need to add teleports, so it's fine. Our earlier logic that we output -1 if any component lacks non-negative nodes applies only when we need to connect that component to others? Actually, consider the case: graph already connected, but all nodes have negative C. The GFA does not need to make any teleports. They can travel via spaceways. So the plan is fulfilled with 0 cost. So answer should be 0. So we need to refine: The requirement for a component to have a non-negative node is only if that component is not already connected to the rest (i.e., if there is more than one component). More precisely, we need to add teleports to connect the components. For a component that has no allowed node, we cannot attach a teleport to it, so it cannot be connected to any other component. Therefore, if there is more than one component, every component must have at least one allowed node. If there is exactly one component (k=1), we don't need teleports, so allowed nodes are irrelevant. So the condition for impossibility is: if number of components > 1 and there exists at least one component with no allowed node, then impossible. Conversely, if number of components == 1, answer 0 regardless of allowed nodes.
Thus we need to adjust: After computing components, we count the number of components k (distinct roots). If k == 1: output 0 and exit. Else (k > 1): we need to check that every component has at least one allowed node. If any component lacks, output -1. Otherwise, compute total as above.
This resolves the scenario with all negatives but connected.
But what about the scenario where k>1 and some component lacks allowed nodes, but that component might be connected via spaceways? No, it's a separate component, so not connected.
Thus the condition is as above.
Now, what about the scenario where k>1 and all components have allowed nodes, but some component's allowed nodes have very high cost? That's okay.
Now, we need to confirm sample2: k=2 >1, component {2,3} has no allowed node, so -1. Good.
Now, test: N=2, M=0 (two isolated nodes). Costs: -5, -5. k=2 >1, both components have no allowed node? Each component (each node) has no allowed node because C<0. So impossible: -1. But is that correct? Could they connect them without teleports? No, they are isolated. They would need to add a teleport. But any teleport would involve an endpoint at one of the nodes, which are type2 and forbidden. So they cannot connect them. So answer -1. That makes sense.
Now test: N=2, M=0, costs: -5, 10. Two components: component1 (node1) negative, component2 (node2) positive. k=2 >1, component1 lacks allowed node, so -1. Indeed, we cannot connect node1 because any teleport to node1 would involve endpoint at node1 which is forbidden. So impossible. So -1.
Now test: N=2, M=0, costs: 0, 10. Both allowed, k=2, mins [0,10], sum=10, (2-2)=0 =>10. Teleport cost 0+10=10. So answer 10.
Now test: N=2, M=1 (edge connecting them). k=1 =>0.
Now test: N=3, M=2 edges: 1-2, 2-3 -> k=1 =>0 regardless of costs.
Now test: N=3, M=1 edge: 1-2. Components: {1,2} and {3}. Costs: all negative: -1,-2,-3. k=2 >1. Component {1,2} has no allowed? Both negative -> no allowed. Component {3} negative -> no allowed. So -1. Could we connect component {3} to component {1,2} without teleports? No, because no edge. So -1.
Now test: N=3, M=1 edge: 1-2. Costs: -1, -2, 5. Components: {1,2} both negative -> no allowed; {3} allowed. k=2, component {1,2} has no allowed, so -1.
Thus condition holds.
Now, implement accordingly.
Now, we must be careful about DSU and reading input.
Now, consider the possibility that there are multiple edges and self-loops? Not present.
Now, also consider that M can be 0.
Now, test with a large case to ensure performance.
Now, an alternative way: Use DFS to find components, but DSU is easier.
Now, we need to compute the number of components efficiently. After unions, we can count number of distinct roots by iterating i and checking if parent[i]==i after path compression. But note that we may not have compressed all nodes. So before counting, we can call find(i) for all i to compress, or we can just use find(i) when processing costs and then later use parent[i] if we are sure compression happened. To be safe, after processing all edges, we call find(i) for all i to set parent[i] to root. Or we can do it in the cost loop: For each i, r = find(i) (which compresses), then update data. After that loop, the parent array may still have some nodes not fully compressed (because find(i) returns root but may not set parent of all intermediate nodes? Actually find(i) with path compression typically sets parent of i to root, but intermediate nodes on the path might not be updated if recursion is not full? In iterative implementation, we can compress path from i to root, so after call, parent[i] = root. But other nodes on the path (like the previous parent) may not be updated. However, when we later check parent[i]==i to determine roots, we need to ensure that for root nodes, they still point to themselves. That's fine. For non-root nodes, they point to some node that may not be root if we didn't compress the whole chain. But if we called find(i) for each i, then each i's parent becomes the root directly (assuming we implement find with full path compression). For example, typical iterative with path compression:
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
This compresses the path for the node x, but not necessarily all ancestors. However, after this, parent[x] is the root. For other nodes that were not visited, they may still point to an intermediate. But when we later iterate i from 0 to N-1 and check if parent[i]==i, some nodes may have parent[i] not equal to i but that parent[i] might not be a root if we didn't compress that ancestor. For example, if we have chain 1->2->3, where 3 is root. We call find(1): it will set parent[1] = parent[2] (which is 3) after one step? Let's simulate: Initially parent[1]=2, parent[2]=3, parent[3]=3. In find(1): while parent[1]!=1: parent[1] = parent[parent[1]] = parent[2]=3; then x = parent[1] =3; now parent[1]=3, x=3, loop ends, return 3. So after that, parent[1]=3, parent[2] remains 2. So node 2's parent is still 2? Actually parent[2] is 2? Wait we had parent[2]=3 originally? I said parent[2]=3. That is wrong: In DSU, parent stores parent pointer; if 2's parent is 3, then parent[2]=3. So in find(1), parent[1] becomes parent[parent[1]] = parent[2] = 3. So parent[1]=3. parent[2] remains 3. So now parent[2]=3, which is root. So it's fine: node 2 still points to root. Actually it's okay because parent[2] = 3 (root). So after calling find on all nodes, each node will either point directly to root or to a node that points to root (if we didn't compress that node). But that node's parent may be root. So checking parent[i]==i will still correctly identify only roots. However, if we didn't call find on some node, that node might have parent[i] = some non-root node that is not root. For instance, if we never call find(2) in the above chain, and we called find(1) only, then parent[1]=3, parent[2]=3? Actually if union set root 3, and we never called find on 2, after union we might have parent[2]=3 directly from union operation? In union, we set parent of one root to another, so only roots are modified. The internal nodes (non-root) remain pointing to their parent. For node 2, if it's not a root, its parent is whatever was set before. In typical DSU, after union operations, we maintain that each set has a root, and all nodes eventually have parent that leads to the root. If we never call find on a node, it may have a parent that is not the root (i.e., an intermediate). But that intermediate's parent is a root? Possibly. Actually in union, we always attach root of one set to root of another, so all nodes that were originally in a set have parent pointers that eventually lead to some root, but some may not be direct. However, after we call find(i) for all i in cost processing, each i's parent becomes the root (due to path compression in find). So after that loop, all nodes have parent = root. So then checking parent[i]==i will correctly identify roots. So we should call find(i) for each i when processing costs. That ensures compression. Then after the loop, we can iterate i and check if parent[i]==i to get roots.
Alternatively, we could keep a set of roots by using the result from find(i) during cost processing: we can store the root for each i, and then later collect unique roots. That might be simpler: we can have a dictionary mapping root to min_cost. While iterating nodes, we get root = find(i). Then update min_cost for that root. Also we could increment a count of components if root not seen before. But careful: if we use a dict, we need to later compute sum and min. That's also O(N) and may be simpler. But DSU already gives us root, so we can use a dict keyed by root integer. However, using a dict may have overhead but N=100k is fine. However, to avoid overhead, using arrays might be fine. But we need to know which roots are present. Since after find(i) for all i, we can collect roots by iterating i and checking if parent[i]==i.
I'll go with array approach:
Initialize min_cost = [None] * N # or maybe a large sentinel like INF, but we need to differentiate None
After processing edges, for i in range(N):
r = find(i) # compress
if C[i] >= 0:
if min_cost[r] is None or C[i] < min_cost[r]:
min_cost[r] = C[i]
After loop, set roots = [].
for i in range(N):
if parent[i] == i: # after find on all, should be root
if min_cost[i] is None:
# component has no allowed node
# but we need to check if k>1? Actually we'll count k later.
# We'll just note that this component has no allowed.
# But we need to decide based on k.
else:
roots.append(i) ??? Actually we need to store min_cost for each root. But if min_cost[i] is None, that component has no allowed.
But careful: If k==1 and the only component has no allowed, min_cost[root] is None. Then roots list would be empty if we only include those with min_cost not None. But we need to detect k==1. So better: first compute list of all roots (i where parent[i]==i). Count k = number of such i. If k == 1, output 0 and exit. Else, for each root i, check if min_cost[i] is None. If any is None, output -1. Else compute sum and min.
That works.
Implementation details:
- We'll compress all nodes by calling find(i) for each i maybe during the cost processing, which also updates min_cost. Then after that loop, we can again iterate i to identify roots. However, note that after the cost processing, we have called find(i) for each i, which updates parent[i] to root. So parent[i] will be root for all i. So for root nodes, parent[root] might be itself. But also note that for a root node r, when we called find(r), it will return r and parent[r] remains r. So that's fine.
Thus after cost processing, we can do:
roots = []
for i in range(N):
if parent[i] == i:
roots.append(i)
k = len(roots)
if k == 1:
print(0)
return
Now, for each r in roots:
if min_cost[r] is None:
print(-1)
return
Then compute sum_mins = sum(min_cost[r] for r in roots), global_min = min(min_cost[r] for r in roots), ans = sum_mins + (k-2) * global_min.
Now, we must ensure that min_cost[r] is defined for all roots when k>1. The check ensures that.
Now, test with scenario: k=1, all negative: roots = [some root], min_cost[root] is None, but we output 0 before checking min_cost. That's correct.
Now, scenario: k>1, all negative: roots will have multiple entries, each with min_cost None. We'll go to check and output -1. Good.
Now, scenario: k>1, some positive, some negative: if any root has min_cost None -> -1.
Now, scenario: k>1, all positive: fine.
Now, what about a component that has allowed nodes but also negative nodes? min_cost defined, fine.
Now, one more nuance: Is it possible that a component has allowed nodes but all allowed nodes have cost 0? That's fine.
Now, edge case: Could there be a component that has allowed node with cost 0, and that component is the only component? k=1 -> 0.
Now, all good.
Now, let's consider if there could be any benefit to using a node with cost higher than min in a component if that node also belongs to another component? No, each node belongs to exactly one component.
Thus algorithm complete.
Now, we need to ensure we handle input efficiently. We'll use sys.stdin.buffer.read() and map to ints. Since M up to 1e6, total numbers = 2 + 2*M + N, which could be up to 2+2e6+1e5 = about 2.1e6 numbers, which is fine.
Implementation:
import sys
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
N = int(next(it))
M = int(next(it))
parent = list(range(N))
rank = [0]*N
def find(x):
# iterative with path compression
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a,b):
ra = find(a)
rb = find(b)
if ra == rb:
return
if rank[ra] < rank[rb]:
parent[ra] = rb
elif rank[ra] > rank[rb]:
parent[rb] = ra
else:
parent[rb] = ra
rank[ra] += 1
for _ in range(M):
a = int(next(it)) - 1
b = int(next(it)) - 1
union(a,b)
# read costs
C = [int(next(it)) for _ in range(N)]
# Initialize min_cost array with None
min_cost = [None] * N
# For each node, update min_cost for its component
for i in range(N):
r = find(i) # compress
if C[i] >= 0:
cur = min_cost[r]
if cur is None or C[i] < cur:
min_cost[r] = C[i]
# Now collect roots
roots = []
for i in range(N):
if parent[i] == i: # after find calls, should be root
roots.append(i)
k = len(roots)
if k == 1:
print(0)
return
# Check for any component without allowed node
for r in roots:
if min_cost[r] is None:
print(-1)
return
# Compute sum and min
total = 0
min_global = None
for r in roots:
mc = min_cost[r]
total += mc
if min_global is None or mc < min_global:
min_global = mc
ans = total + (k - 2) * min_global
print(ans)
if name == "main":
main()
Now, test with sample.
Sample1:
N=6, M=6, edges given, unions form two components. Costs all positive. After cost processing, min_cost for root1 = 1, root2 = 2. roots list: two roots. k=2 >1, both min defined. total=3, min_global=1, ans = 3 + (0)*1 =3. Print 3.
Sample2:
N=3, M=1, union(2-3). After unions, components: root for 2 and 3 same; root for 1 separate. Costs: 1, -1, -1. Process nodes: node0 (1) C=1 >=0, find root = root0 -> min_cost[root0]=1. node1 (2) C=-1 skip; node2 (3) C=-1 skip. So min_cost for root1 (component of 2,3) remains None. roots: two roots (0 and say root of 2). k=2 >1. Check: root1 min_cost None -> print -1.
Good.
Now, test scenario: N=3, M=2 edges: 1-2,2-3 (connected). After unions, one component. roots: one root. k=1 -> print 0 regardless of costs. Works.
Now, test scenario: N=3, M=0, all negative. Process: each node isolated, so roots: 3 roots. k=3>1. For each root, min_cost is None (since all negative). Check: any root with None -> print -1. That's correct.
Now, test scenario: N=3, M=0, costs: -1, 5, 6. Roots: three roots. root0 (node0) min_cost None -> -1. Because node0 is negative, component with only negative cannot be connected. So -1.
Now, test scenario: N=4, M=2 edges: 1-2, 3-4. Costs: -1,5, -2,6. Components: comp1 {1,2}: has node2 with 5, so min_cost=5. comp2 {3,4}: node4 with 6, min_cost=6. roots: 2. k=2>1, both defined, total=11, ans=11? Actually min_global=5, ans = 11 + (0)*5 =11. But we can add teleport between node2 (cost5) and node4 (cost6) = 11. That's correct.
Now, test scenario: N=4, M=2 edges: 1-2, 3-4. Costs: -1,5, -2,0. comp2 min=0, comp1 min=5, total=5, ans=5? Wait total = 5+0=5. ans = 5 + (0)*0 =5. Teleport between node2 (5) and node4 (0) =5. Works.
Now, test scenario: N=4, M=0, costs: 1,2,3,4. k=4, total=10, min_global=1, ans=10+ (2)*1=12. As earlier.
Now, test scenario: N=4, M=0, costs: 0,0,0,0 => total=0, ans=0+ (2)*0=0. Good.
Now, test scenario: N=1, M=0, cost any (including negative). k=1 -> 0. That seems plausible: with one planet, no travel needed, so no teleports, cost 0. Good.
Now, what about the possibility that some component has allowed node but its min is very large, and the global min is from another component. That's fine.
Now, we should double-check if the MST over components with edge cost = min_i + min_j indeed yields the formula we used. Let's derive: In a tree with k nodes (components) where edge weight between i and j is w_ij = m_i + m_j, the total weight = sum_{edges} (m_i + m_j) = sum_i m_i * deg_i. Since sum deg_i = 2(k-1), the total is minimized when we assign higher degrees to smaller m_i. The optimal is to give degree k-1 to the smallest m, and degree 1 to all others. So total = m_min*(k-1) + sum_{i != min} m_i1 = m_min(k-1) + (sum_i m_i - m_min) = sum_i m_i + (k-2)*m_min. That's our formula.
Thus correct.
Now, consider whether we could have a cheaper solution by not connecting components directly but instead using a chain of teleports that go through intermediate planets within the same component? But that's the same as connecting components directly: a teleport is an edge. A chain of teleports connecting component A to component B via component C still uses two teleports: A-C and C-B. The total cost would be (m_A + m_C) + (m_C + m_B) = m_A + m_B + 2m_C, which is generally >= m_A + m_B + m_C + m_min? Actually star cost: m_A + m_B + 2m_min if min is the hub. If m_C is larger than m_min, star using min is cheaper. If m_C is min, then it's same as star (since min is hub). So the tree approach is optimal.
Thus the answer is robust.
Now, we must ensure that we treat the case where there is at least one component with no allowed node, but k>1, output -1.
Now, confirm that we considered all constraints.
Now, test some random cases with small N to validate via brute force? Not necessary but we can reason.
Now, let's also think about if there could be any scenario where we could use a teleport between two nodes in the same component to reduce cost? That would not help connectivity.
Now, final check: Input format: after M lines of edges, there are N lines of C. Yes.
Now, about fast I/O: we used sys.stdin.buffer.read().split() which reads all data into memory. That is fine for up to ~2 million numbers, each maybe a few bytes, memory okay.
Now, potential issue: When reading numbers, we convert to int per token. That's fine.
Now, confirm DSU find function: We used iterative with path compression that sets parent[x] = parent[parent[x]] inside while. This is good.
Now, test with a scenario where rank is used: It's fine.
Now, we need to be careful: In the cost loop, we call find(i) for each i. This will compress paths. At the end, all nodes point to root. However, the roots themselves might not be compressed? They are roots, so parent[root] = root. That's fine.
Now, after that, we iterate i to collect roots with parent[i]==i. That gives all roots correctly.
Now, one more nuance: There might be components that are isolated (no edges) but have allowed nodes; those are separate components. That's fine.
Now, we need to output -1 if impossible, else integer.
Now, check if there could be a case where global min is from a component that has multiple nodes but also includes negative nodes; that's fine.
Now, we should also consider that the cost of a teleport is sum of endpoint costs, but what about the possibility of using a node with cost 0 multiple times? That adds 0 each time, so no issue.
Now, we should also consider if the GFA could avoid paying tax by not using teleports at all? But they need to make the graph connected. If it's already connected, no teleports. So fine.
Now, final answer is ready.
But wait: There's a subtlety: The problem statement says: "The GFA would always avoid such governments no matter what the consequences are". Does that mean they will not make any teleport that ends at those planets, even if it means the plan cannot be fulfilled? In our logic, if a component has no allowed nodes but k>1, we output -1, meaning plan cannot be fulfilled. That matches "no matter what the consequences are" i.e., they would rather not fulfill the plan than engage with them? But the plan is to have all teams able to reach any planet; if they can't achieve it without engaging type2, then they cannot fulfill, so output -1. So consistent.
Now, think about a scenario where there are multiple components, but one component has no allowed nodes, but maybe it's possible to connect that component to others via a teleport that ends at a node in that component? But that would involve using a type2 government, which they avoid. So indeed impossible.
Thus final.
Now, we need to ensure we correctly handle the case where there is at least one allowed node in each component but the global min is from a component, but what if the global min is 0? Then total = sum(m_i) + (k-2)*0 = sum(m_i). That's okay.
Now, edge case: k>1 and one component has min huge, but okay.
Now, let's test with random small N and brute force enumeration to confirm formula? Not necessary for solution but could mentally.
Now, there might be a twist: The teleport is bidirectional; but maybe the tax is paid only once per planet regardless of number of teleports? Let's re-express: "if it wants to make a teleport ending at their planet." This phrasing might be interpreted as: if the GFA decides to build a teleport that has an endpoint on that planet, then it must pay the tax (or receive money) for that teleport. So per teleport. However, could it be that they pay the tax when they "make a teleport ending at their planet", i.e., they pay the government to allow the teleport to be built. That payment could be a one-time fee for that teleport. So yes per teleport. Not per planet activation.
Thus formula stands.
Now, confirm with known problems: I recall a CodeChef problem "GALACTIK" where you have to connect components with cost = A[i] + A[j] and negative costs are allowed but you have to pay. However, in that problem, you could also use negative cost nodes and the answer could be negative; but there was a condition about needing at least one positive? Actually I think there is a known problem "Galactik Football" on SPOJ (SPOJ GALACTIK). Let me recall: In that problem, each planet has a cost (can be negative). The goal is to make the graph connected by adding edges, where adding an edge between u and v costs C[u] + C[v]. If a planet has negative cost, it means they pay you. But you cannot add an edge to a planet with cost < 0 if you haven't already added an edge to some positive cost? Hmm not sure. Actually I think the SPOJ problem is similar but the solution involves: if any component has all negative costs and no positive, you might need to treat differently. However, let's search memory: I recall a problem where you have to find minimum cost to connect graph using edges with weight equal to sum of node weights, and negative weights are allowed. The solution was: For each component, find the minimum cost node (including negative). If there is at least one component where all nodes are negative, then you can get money from them, but you also need to connect them. Actually the typical solution: If there is at least one positive cost node somewhere, you might want to connect all components via the node with smallest cost (could be negative). But the problem statement we have includes the phrase "The GFA would always avoid such governments no matter what the consequences are", which changes the interpretation: negative costs are to be avoided. So it's not the standard problem.
Let's search online memory: "Galactik Football" problem appears on CodeChef (I think it's from Amritapuri 2008). I recall reading editorial: The solution is to compute connected components, find minimum A in each component, and if any component has all negative, then you might need to handle specially. But in many versions, negative costs are allowed and can reduce total. However, this particular problem statement includes the "avoid" clause, which makes it different. Since we have sample2 with -1 -1 and answer -1, that matches the avoidance. So it's a variation.
Given that sample2 includes negative costs and output -1, it's clear that negative costs are not allowed as endpoints.
Thus we have the correct interpretation.
Now, let's implement final code with proper I/O.
Now, I realize: In our DSU, after processing edges, we need to call find(i) for all i to compress, which we do in cost loop. But before cost loop, we haven't compressed, so for each i we call find(i). That's fine.
Now, what about the possibility that a component has only one node with allowed cost, but that node is also the root? That's fine.
Now, confirm that we didn't forget to update min_cost for nodes that have C=0. Since C>=0 includes 0.
Now, one more nuance: What about the scenario where k>1 and there is exactly one component with allowed nodes, and all other components have no allowed nodes? Then we would output -1 because at least one component lacks allowed. That is correct, because we cannot connect the components without using teleports to those forbidden components.
Now, test: N=3, M=0, costs: 5, -1, -1. Three components: comp1 allowed, comp2 forbidden, comp3 forbidden. k=3 >1, comp2,comp3 no allowed -> -1. Indeed impossible because you can't connect to -1 nodes.
Now, test: N=3, M=1 edge: 2-3. So components: {2,3} and {1}. Costs: 5, -1, -1. comp {2,3} has no allowed -> -1.
Thus consistent.
Now, we need to ensure that we output integer without extra spaces.
Now, let's think about large N and M; DSU with recursion depth might be an issue if we use recursive find, but we use iterative.
Now, there is a potential issue: In the cost loop, we update min_cost for root r. But we used min_cost array of size N, indexed by root id (which is an integer). Since we call find(i) for each i, r is the root. However, if later we call find on another node that changes the root of some set? No, after union operations, the structure is static; find with path compression may change parent pointers, but the root id remains consistent. So min_cost for that root is fine.
Now, one more nuance: After we call find(i) for each i, we might have updated parent[i] to root, but the root's own parent remains itself. So when we later iterate to collect roots, we check parent[i]==i. For root nodes, this holds. For non-root nodes, parent[i] != i. So we get roots correctly.
Now, we need to be careful that we have not inadvertently changed root of a component during the cost loop? No, find does not change the root.
Now, all good.
Now, test with random input:
N=5, M=2 edges: 1-2, 3-4. So components: {1,2}, {3,4}, {5}. Costs: 2,3, -1,5,0. Component1 min = 2 (since 2 and 3, min 2). Component2: nodes 3 (-1) and 4 (5) -> min =5 (since -1 not allowed). Component3: node5 cost 0 -> min=0. So k=3>1, all have allowed. sum = 2+5+0=7, min_global=0, ans = 7 + (1)*0 =7. Let's compute manually: Connect components. The cheapest is to use node5 (cost0) as hub: edges: connect 5 to component1: choose node1 cost2? Actually min in comp1 is 2, so edge cost 0+2=2. Connect 5 to component2: choose node4 cost5, edge cost 0+5=5. Total=7. Could we do differently? Connect comp1 to comp2: 2+5=7, then connect that combined to comp3: min of combined? If we first connect comp1 and comp2 via nodes 2 and 5? Actually after connecting comp1 and comp2, the combined component's min allowed node is min(2,5)=2 (or maybe 2 if we consider both nodes still available). But to connect to comp3, we would need a teleport from some node in combined to node5. The cheapest node in combined is 2, so edge cost 2+0=2. Total = 7+2=9? Wait we need to be careful: If we first add teleport between comp1 and comp2 (cost 2+5=7), then we have a component containing {1,2,3,4} with allowed nodes 2 and 5? Actually node4 cost5, node2 cost2, node1 cost3, node3 negative. So min allowed =2. Then add teleport between that component and comp3: cost 2+0=2. Total=9. So star is better. So 7 is optimal. So formula works.
Now, check if using node3 (negative) is not allowed, so correct.
Thus answer.
Now, we should also consider if there is any component where the min allowed node is the same as global min, but that component also contains other allowed nodes; star still works.
Now, verify that the formula works for k=2: total = sum_mins, because (k-2)=0.
Now, check for k=0 (not possible).
Now, we need to handle large input efficiently, especially M up to 1e6. DSU union operations with path compression and union by rank will be fine.
Now, one potential optimization: we could compress all nodes after reading edges by calling find(i) for all i to set parent[i] before cost loop. But we already do that during cost loop.
Now, ensure that we convert indices to 0-based.
Now, I think it's done.
Now, let's consider alternative approach: If we use DFS, we would need to store adjacency list, which could be large (M up to 1e6, edges are bidirectional, adjacency list size 2M = 2e6). That's acceptable memory wise (2e6 ints ~ 16 MB). But DSU doesn't need adjacency list; it's more memory efficient. However, DSU also needs parent and rank arrays, which is 2*N ints ~ 0.8 MB. So DSU is fine.
But we need to read edges anyway to union them. We can just read and union without storing adjacency list.
Thus DSU is simpler.
Now, let's finalize.
But before finalizing, let's double-check the condition for impossibility: If k>1 and any component has no node with C>=0, output -1. However, what if there is a component with no allowed node but that component is actually already connected to another component via a teleport? But to connect via teleport, we need a teleport endpoint on that component, which is not allowed. So impossible. So correct.
Now, what if there is a component with no allowed node but it is the only component? k=1, so fine.
Now, one more nuance: The graph might have self-loops or multiple edges; not relevant.
Now, final code as above.
Now, test with a tricky case: N=2, M=0, costs: 0, -5. k=2>1. Component1 (node1) has allowed (0). Component2 (node2) has no allowed (negative). So output -1. Indeed, cannot connect without using node2 as endpoint. So -1.
Now, test with N=2, M=0, costs: 0, 0. Both allowed, k=2, total=0, ans=0. Teleport between two zero cost nodes costs 0, so graph connected cost 0. That's fine.
Now, test with N=2, M=0, costs: 5, 5. total=10, ans=10.
Now, test with N=2, M=0, costs: 5, -1 -> -1.
Now, test with N=2, M=1, costs: 5, -1 -> connected, k=1 -> 0. Yes, because they are already connected via spaceway (edge). So no teleport needed.
Thus good.
Now, we must consider that there could be a teleport that ends at a planet with negative cost (type2) if the GFA absolutely has to, but they avoid them, meaning they won't do it. The problem statement: "The GFA would always avoid such governments no matter what the consequences are". This implies that they would not make such a teleport even if it means failure. So the plan is considered not fulfillable if the only way to connect involves using a type2 planet. So our handling is correct.
Now, but there might be an interpretation: They avoid such governments, meaning they won't accept money from them, so they won't make teleports ending there if it results in receiving money? But if they are forced to use them, they might still do it but not accept the money? That doesn't make sense. The phrase is ambiguous. However, sample2 confirms that they output -1 when there are negative costs and multiple components, indicating that they cannot avoid using them? Actually sample2: components: {2,3} both negative, {1} positive. They would need to connect {1} to {2,3}. They could choose to make a teleport between 1 and 2, costing 1 + (-1)=0, but they avoid type2? The answer is -1, meaning they can't. So they avoid using negative nodes entirely. So we are correct.
Now, what if there were a component with both positive and negative nodes? Then they can use the positive nodes only. That's fine.
Thus final.
Now, produce final answer.
But before final, think about the possibility that the graph is already connected, but there are type2 governments; we output 0. That matches "avoid" because we don't engage them.
Now, edge case: N=0? Not.
Now, check for potential overflow: Python int fine.
Now, finalize.
Now, we should test with a case where there are many components and some components have min cost large, to ensure formula works.
Now, I think it's ready.
Now, let's write final code with appropriate imports and structure.
We'll also add a small optimization: Use sys.stdout.write for output.
Now, final code:
import sys
def main():
import sys
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
m = int(next(it))
parent = list(range(n))
rank = [0]*n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a,b):
ra = find(a)
rb = find(b)
if ra == rb:
return
if rank[ra] < rank[rb]:
parent[ra] = rb
elif rank[ra] > rank[rb]:
parent[rb] = ra
else:
parent[rb] = ra
rank[ra] += 1
for _ in range(m):
a = int(next(it)) - 1
b = int(next(it)) - 1
union(a,b)
costs = [int(next(it)) for _ in range(n)]
min_cost = [None] * n
for i in range(n):
r = find(i)
c = costs[i]
if c >= 0:
cur = min_cost[r]
if cur is None or c < cur:
min_cost[r] = c
roots = [i for i in range(n) if parent[i] == i] # after find calls, parent[i] is root
k = len(roots)
if k == 1:
sys.stdout.write("0")
return
for r in roots:
if min_cost[r] is None:
sys.stdout.write("-1")
return
total = 0
global_min = None
for r in roots:
mc = min_cost[r]
total += mc
if global_min is None or mc < global_min:
global_min = mc
ans = total + (k - 2) * global_min
sys.stdout.write(str(ans))
if name == "main":
main()
Now, final answer. ```python
import sys
def main():
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
m = int(next(it))
# ---------- DSU ----------
parent = list(range(n))
rank = [0] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra = find(a)
rb = find(b)
if ra == rb:
return
if rank[ra] < rank[rb]:
parent[ra] = rb
elif rank[ra] > rank[rb]:
parent[rb] = ra
else:
parent[rb] = ra
rank[ra] += 1
# read edges
for _ in range(m):
a = int(next(it)) - 1
b = int(next(it)) - 1
union(a, b)
# read costs
cost = [int(next(it)) for _ in range(n)]
# ---------- find minimum non‑negative cost per component ----------
min_cost = [None] * n # None means "no allowed node yet"
for i in range(n):
r = find(i) # path compression happens here
if cost[i] >= 0:
cur = min_cost[r]
if cur is None or cost[i] < cur:
min_cost[r] = cost[i]
# ---------- collect roots ----------
roots = [i for i in range(n) if parent[i] == i] # after all find calls
k = len(roots)
if k == 1:
# already connected, no teleport needed
sys.stdout.write("0")
return
# ---------- check feasibility ----------
for r in roots:
if min_cost[r] is None: # component without any allowed node
sys.stdout.write("-1")
return
# ---------- compute answer ----------
total = 0
global_min = None
for r in roots:
mc = min_cost[r]
total += mc
if global_min is None or mc < global_min:
global_min = mc
ans = total + (k - 2) * global_min
sys.stdout.write(str(ans))
if name == "main":
main()