poj 2075 lightblueme double qsort cmp函数的写法

对于int类型的数据使用qsort可以为:

int a,b;

int cmp(){

     return a-b;

}

而对于double类型

int a,b;
if(a>b)
    return 1;
if(a==b)
    return 0;
else
    return -1;

poj 2075 code

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define NUM 1005
using namespace std;

typedef struct{
	int from,to;
	double cost;
}Edge;

Edge edges[NUM*NUM];
int cmp(const void * a,const void * b){
	Edge aa=*((Edge *)a);
	Edge bb=*((Edge *)b);
	int t;
	if(aa.cost>bb.cost){
		t=1;
	}
	if(aa.cost==bb.cost){
		t=0;
	}
	if(aa.cost<bb.cost){
		t=-1;
	}
	return t;
}
int root[NUM];
void init(){
	for(int index=0;index<NUM;index++){
		root[index]=index;
	}
}

int findroot(int a){
	if(a!=root[a]){
		root[a]=findroot(root[a]);
	}
	return root[a];
}

void unionroot(int a,int b){
	root[a]=b;
}


char names[NUM][21];

char name1[21];
char name2[21];
double path;

int main(){
	double L;
	int N;
	scanf("%lf",&L);
	scanf("%d",&N);
	for(int i1=0;i1<N;i1++){
		scanf("%s",names[i1]);
	}
	
	int M;
	scanf("%d",&M);
	int index=0;
	for(int i2=0;i2<M;i2++){
		scanf("%s",name1);
		scanf("%s",name2);
		scanf("%lf",&path);
		edges[index].cost=path;
		for(int k=0;k<N;k++){
			if(strcmp(name1,names[k])==0){
				edges[index].from=k;
			}
			if(strcmp(name2,names[k])==0){
				edges[index].to=k;
			}
		}
		index++;
	}
	qsort(edges,M,sizeof(Edge),cmp);

	int edgenum=0;
	double sum=0;
	init();
	for(index=0;index<M;index++){
		int a=edges[index].from;
		int b=edges[index].to;
		int root1=findroot(a);
		int root2=findroot(b);
		if(root1!=root2){
			unionroot(root1,root2);
			edgenum++;
			sum+=edges[index].cost;
			if(edgenum==N-1)
				break;
		}
	}
	if(L>=sum){
		printf("Need %.1f miles of cable\n",sum);
	}
	else{
		printf("Not enough cable\n");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值