1 solutions

  • 0
    @ 2025-3-3 16:24:08

    C++ :

    #include<stdio.h>
    #include<algorithm>
    using namespace std;
    
    struct vi
    {
    	int start;
    	int end;
    	int cost;
    }edge[130000],et;
    
    int p[500];
    
    int Find(int n)
    {
    	return n==p[n]?n:p[n]=Find(p[n]);
    }
    
    bool cmp(vi a,vi b)
    {
    	return a.cost<b.cost;
    }
    
    int main()
    {
    	int t,n,e,i,k,sum,ST,EN;
    	scanf("%d",&t);
    	while(t--)
    	{
    		scanf("%d%d",&n,&e);
    		for(i=0;i<n;i++)
    			p[i]=i;
    		for(k=i=0;i<e;i++)
    		{
    			scanf("%d%d%d",&et.start,&et.end,&et.cost);
    			if(et.cost==0)
    				p[Find(et.start)]=Find(et.end);
    			else
    				edge[k++]=et;
    		}
    		sort(edge,edge+k,cmp);
    		for(sum=i=0;i<k;i++)
    		{
    			ST=Find(edge[i].start);
    			EN=Find(edge[i].end);
    			if(ST!=EN)
    			{
    				p[ST]=EN;
    				sum+=edge[i].cost;
    			}
    		}
    		printf("%d\n",sum);
    	}
    	return 0;
    }
    

    Java :

    import java.util.*;
    public class Main {
    	private static Scanner in;
    
    	public static void main(String[] args) {
    		in = new Scanner(System.in);
    		int i,t,n,e,j,f,o,h,g,temp1,temp2,current;
    		int a,b,m,mm,k,min,mincost,minIndex=0;
    		int[][] nextArray;
    		ArrayList<Integer> U = new ArrayList<Integer>();
    		ArrayList<Integer> V = new ArrayList<Integer>();
    		t = in.nextInt();
    		for(i = 1;i <= t;i++){
    			mincost = 0;
    			U.clear();
    			V.clear();
    			n = in.nextInt();
    			e = in.nextInt();
    			nextArray = new int[n][n];
    			for( m = 0;m < n;m++)
    				for( mm = 0;mm < n;mm++)
    					nextArray[m][mm]=-1;
    			for( j = 0;j < e;j++) {
    				a = in.nextInt();
    				b = in.nextInt();
    				k = in.nextInt();
    				nextArray[a][b]=k;
    				nextArray[b][a]=k;
    			}
    			U.add(0);
    			for (f = 1;f < n;f++)
    				V.add(f);
    			for( o = 1;o < n;o++) {
    				min = 1000;
    				for( h = 0;h < U.size();h++) {
    					    temp1=U.get(h);
    					for(g=0;g < V.size();g++) {
    					    temp2 = V.get(g);
    						current = nextArray[temp1][temp2];
    						if(current != -1 && current < min) {
    							min = current;
    							minIndex = g;
    						}
    					}
    				}
    				mincost += min;
    				U.add(V.get(minIndex));
    				V.remove(minIndex);
    			}
    			System.out.println(mincost);
    		}
    
    	}
    }
    
    
    • 1

    Information

    ID
    10011
    Time
    1000ms
    Memory
    32MiB
    Difficulty
    (None)
    Tags
    # Submissions
    0
    Accepted
    0
    Uploaded By