Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package mst;
- /**
- *
- * @author Hp
- */
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.*;
- class kru{
- int i,j,k,a,b,u,v,n,ne=1;
- int min,mincost=0;
- int cost[][]=new int[1000][1000];
- int parent[]=new int[1000];
- kru(int n,int e,Scanner sc){
- for(i=1;i<=e;i++)
- {
- int x=sc.nextInt();
- int y=sc.nextInt();
- int q=sc.nextInt();
- cost[y][x]=cost[x][y]=q;
- }
- for(i=1;i<=n;i++)
- {
- for(int ji=1;ji<=n;ji++)
- {
- if(cost[i][ji]==0)
- cost[i][ji]=999;
- }
- }
- while(ne < n)
- {
- for(i=1,min=999;i<=n;i++)
- {
- for(j=1;j <= n;j++)
- {
- if(cost[i][j] < min)
- {
- min=cost[i][j];
- a=u=i;
- b=v=j;
- }
- }
- }
- u=find(u);
- v=find(v);
- if(uni(u,v)!=0)
- {
- System.out.println(a+" "+b);
- ne++;
- mincost +=min;
- }
- cost[a][b]=cost[b][a]=999;
- }
- System.out.println("min_cost"+mincost);
- }
- int find(int i)
- {
- while(parent[i]!=0)
- i=parent[i];
- return i;
- }
- int uni(int i,int j)
- {
- if(i!=j)
- {
- parent[j]=i;
- return 1;
- }
- return 0;
- }
- }
- public class Mst {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) throws FileNotFoundException {
- // TODO code application logic here
- File file=new File("C:\\Users\\Student\\Desktop\\shosho\\mst-2015-10-03\\mst\\src\\mst\\input.txt");
- Scanner sc=new Scanner(file);
- int n=sc.nextInt();
- int e=sc.nextInt();
- kru m=new kru(n,e,sc);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement