我使用了不相交的集合概念来解决这个问题。从访问过的所有挤奶员开始,每当有新分支到达新人时,他被标记为已访问。我已经测试了以下边缘情况:
市内没有挤奶员
每个人都是送奶工
有些送奶工没有与任何人联系
某人与任何人无关
2人之间的多条路径
Milkmen和人正在形成不相交的集合
我还在接受WA。关于遗失案件的任何想法?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by VIVEK VERMA on 9/25/2016.
*/
public class SpojIITWPC4I {
public static void main(String[] arge) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
for (int t = 0; t < T; t++) {
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
int n = Integer.parseInt(tokenizer.nextToken());
int m = Integer.parseInt(tokenizer.nextToken());
int totalIncludedNodes = 0;
ManNode[] people = new ManNode[n];
Queue<ManLink> links = new PriorityQueue<>();
tokenizer = new StringTokenizer(reader.readLine());
for(int i=0;i<n;i++){
int val=Integer.parseInt(tokenizer.nextToken());
people[i] = new ManNode(i);
if(val==1){
people[i].isIncluded = true;
totalIncludedNodes++;
}
}
for(int i = 0; i<m;i++){
tokenizer = new StringTokenizer(reader.readLine());
int start = Integer.parseInt(tokenizer.nextToken()) -1;
int destination = Integer.parseInt(tokenizer.nextToken()) -1;
int value = Integer.parseInt(tokenizer.nextToken());
ManLink link = new ManLink(people[start], people[destination], value);
people[start].AddChild(link);
people[destination].AddChild(link);
if(people[start].isIncluded ^ people[destination].isIncluded){
links.add(link);
}
}
int minCost = 0;
while(!links.isEmpty() && totalIncludedNodes <n){
ManLink link = links.poll();
ManNode nextAddedNode = (link.source.isIncluded==true?link.destinationNode:link.source);
if(nextAddedNode.isIncluded){
continue;
}
minCost += link.value;
nextAddedNode.isIncluded = true;
totalIncludedNodes++;
for(int i=0;i<nextAddedNode.children.size();i++){
if((nextAddedNode.isIncluded ^ nextAddedNode.children.get(i).source.isIncluded)
|| (nextAddedNode.isIncluded ^ nextAddedNode.children.get(i).destinationNode.isIncluded)){
links.add(nextAddedNode.children.get(i));
}
}
}
if(totalIncludedNodes == n){
System.out.println(minCost);
}else{
System.out.println("impossible");
}
}
}
}
class ManNode{
boolean isIncluded = false;
List<ManLink> children = new ArrayList<>();
int index;
ManNode(int index){
this.index = index;
}
void AddChild(ManLink link){
children.add(link);
}
}
class ManLink implements Comparable{
ManNode destinationNode, source;
int value;
ManLink(ManNode source, ManNode node, int value){
this.source = source;
this.destinationNode = node;
this.value = value;
}
@Override
public int compareTo(Object o) {
return this.value - ((ManLink)o).value;
}
}