一道裸的排序题,本应该瞬秒的,结果一直WA在第十组数据上,我很确信我的程序是对的,但就是WA。

后来看了别人的代码,原来错在了qsort与sort的使用上!

大家看一下我WA了8次的代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct P{
    int num;
    double h;
}p[10005];
int cmp( const void *a , const void *b )
{
    struct P *c = (struct P *)a;
    struct P *d = (struct P *)b;
    if(c->h != d->h) return d->h - c->h;
    else return c->num - d->num;
}
int main()
{
    int n;
    double t1,t2,k,a,b;
    while(cin >> n >> t1 >> t2 >>k){
        k=k/100.0;
        for(int i=0;i<n;i++){
            cin >> a >> b;
            double h1=a*t1*(1.0-k)+b*t2;
            double h2=b*t1*(1.0-k)+a*t2;
            if(h1 >= h2){
                p[i].h=h1;
                p[i].num=i+1;
            }
            else{
                p[i].h=h2;
                p[i].num=i+1;
            }
        }
        qsort(p,1000,sizeof(p[0]),cmp);
        for(int i=0;i<n;i++){
            printf("%d %.2lf\n",p[i].num,p[i].h);
        }
    }
    return 0;
}

再看一下我AC的代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
struct P{
    int num;
    double h;
}p[10005];
bool cmp(P x,P y){
    if(x.h==y.h) return x.num < y.num;
    return x.h > y.h;
}
int main()
{
    int n;
    double t1,t2,k,a,b;
    while(cin >> n >> t1 >> t2 >>k){
        k=k/100.0;
        for(int i=0;i<n;i++){
            cin >> a >> b;
            double h1=a*t1*(1.0-k)+b*t2;
            double h2=b*t1*(1.0-k)+a*t2;
            if(h1 >= h2){
                p[i].h=h1;
                p[i].num=i+1;
            }
            else{
                p[i].h=h2;
                p[i].num=i+1;
            }
        }
        sort(p,p+n,cmp);
        for(int i=0;i<n;i++){
            printf("%d %.2lf\n",p[i].num,p[i].h);
        }
    }
    return 0;
}

唯一的差别就在于使用sort还是使用qsort。

事实证明,Codeforces上不支持qsort!!