题面:
思路:
由于存在删边操作,正着来处理可能不太好写,但正难则反,我们可以反向来思考这个问题,我们可以按天数从大到小排序,那么删边操作
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, sc, out);
out.close();
}
static class Task {
public int[] pre;
public int find(int x) {
int temp=x;
while(temp!=pre[temp])
temp=pre[temp];
int i=x,j;
while(i!=temp) {
j=pre[i];
pre[i]=temp;
i=j;
}
return temp;
}
public boolean join(int x,int y) {
int a=find(x);
int b=find(y);
if(a!=b) {
pre[a]=b;
return false;
}
return true;
}
public void solve(int testNumber, InputReader sc, PrintWriter out) throws IOException {
int n=sc.nextInt();
int m=sc.nextInt();
pre=new int[n+1];
for(int i=1;i<=n;i++)
pre[i]=i;
TreeMap<Integer,ArrayList<int[]>> G=new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
for(int i=0;i<m;i++) {
int a=sc.nextInt();
int b=sc.nextInt();
int t=sc.nextInt();
int[] path=new int[2];
path[0]=a;
path[1]=b;
ArrayList<int[]> temp=G.get(t);
if(temp==null)
temp=new ArrayList<int[]>();
temp.add(path);
G.put(t, temp);
}
int ans=0;
for(Map.Entry<Integer, ArrayList<int[]>> temp:G.entrySet()) {
boolean flag=false;
for(int[] p:temp.getValue()) {
if(!join(p[0],p[1])){
if(!flag)
ans++;
flag=true;
}
}
}
out.println(ans);
}
}
static class InputReader{
StreamTokenizer tokenizer;
public InputReader(InputStream stream){
tokenizer=new StreamTokenizer(new BufferedReader(new InputStreamReader(stream)));
tokenizer.ordinaryChars(33,126);
tokenizer.wordChars(33,126);
}
public String next() throws IOException {
tokenizer.nextToken();
return tokenizer.sval;
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean hasNext() throws IOException {
int res=tokenizer.nextToken();
tokenizer.pushBack();
return res!=tokenizer.TT_EOF;
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
}
}
就转化为加边就十分容易处理了。