对于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;
}