今晚在作京東的筆試題時,使用了qsort函數,因爲排序結果不穩定,致使一直沒法ac。後來在待排序的結構體中多加入一個關鍵字段,較簡單的解決了問題。
生日禮物
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Problem Description:
BF的生日快到了,這一次,小東決定爲BF送一份特別的生日禮物爲其慶生。做爲高智商中的佼佼者,BF在國外求學,所以小東沒法與之一塊兒慶生。小東計劃送一個生日卡片,並經過特別的包裝讓BF永遠難忘。ios
她決定把卡片套裝在一系列的信封A = {a1, a2, ..., an}中。小東已經從商店中購買了不少的信封,她但願可以用手頭中儘量多的信封包裝卡片。爲防止卡片或信封被損壞,只有長寬較小的信封可以裝入大些的信封,同尺寸的信封不能套裝,卡片和信封都不能摺疊。函數
小東計算了郵寄的時間,發現她的時間已經不夠了,爲此找你幫忙包裝,你能幫她嗎?
輸入
輸入有若干組,每組的第一行包含三個整數n, w, h,1<=n<=5000, 1<=w, h<=10^6,分別表示小東手頭的信封數量和卡片的大小。緊隨其後的n行中,每行有兩個整數wi和hi,爲第i個信封的大小,1<=wi, hi<=10^6。
輸出
對每組測試數據,結果第一行中輸出最多可以使用的信封數量,結果第二行中按使用順序輸出信封的編號。因爲小東有潔癖,她對排在前面的信封比較有好感,如有多個信封可用,她喜歡用最早拿到的信封。另外別忘了,小東要求把卡片裝入可以裝的最小信封中。
若是卡片沒法裝入任何信封中,則在單獨的行中輸出0。測試
樣例輸入
2 1 1
2 2
2 2
3 3 3
5 4
12 11
9 8
樣例輸出
1
1
3
1 3 2優化
#include<iostream> #include<stdio.h> #include<stdlib.h> using namespace std; struct g { int l; int w; int xu; bool tag; }sticks[5000]; int cmp(const void *a,const void *b) { struct g *c=(g *)a; struct g *d=(g *)b; if(c->l!=d->l) return c->l-d->l; else if(c->w!=d->w) return c->w-d->w; else return c->xu-d->xu; } /* int swap(int &a,int &b){ int t=a; a=b; b=t; return 0; } int partition(int* array,int left,int right) { int index = left; int pivot = array[index]; swap(array[index], array[right]); for(int i=left; i<right; i++) { if(array[i] < pivot)// 降序 swap(array[index++], array[i]); } swap(array[right], array[index]); return index; } void qsort(int* array, int left, int right) { if(left >= right) return; int index = partition(array, left, right); qsort(array, left, index - 1); qsort(array, index + 1, right); }*/ int main() { int i,j,n; int ans,temp; struct g card; while(cin>>n>>card.l>>card.w){ //if(scanf("%d%d%d",&n,&card.l,&card.w)==1) for(i=0;i<n;i++) { sticks[i].tag=false; sticks[i].xu=i+1; scanf("%d%d",&sticks[i].l,&sticks[i].w); } for(i=0;i<n;i++) { sticks[i].tag=false; printf("%d %d %d\n",sticks[i].l,sticks[i].w,sticks[i].xu); } qsort(sticks,n,sizeof(sticks[0]),cmp);// for(i=0;i<n;i++) { sticks[i].tag=false; printf("%d %d %d\n",sticks[i].l,sticks[i].w,sticks[i].xu); } ans=0; int xuhao[5000]; for(i=0;i<n;i++) { if(sticks[i].tag==false) { if(sticks[i].w>card.w&&sticks[i].l>card.l){ xuhao[ans]=sticks[i].xu; ans++; sticks[i].tag=true; } else continue; temp=sticks[i].w; for(j=i+1;j<n;j++) { if(sticks[j].tag==false&&sticks[j].w>temp) { xuhao[ans]=sticks[j].xu; ans++; sticks[j].tag=true; temp=sticks[j].w; } //printf("%d\n",ans); } printf("%d\n",ans); for(int j=0;j<ans;j++){ printf("%d ",xuhao[j]); } printf("\n"); break; } } } return 0; }
在調試時發現一個問題:qsort的結果不穩定,致使對於一些存在相等信封的測試用例輸出錯誤。
優化方法:在待排序的結構體g中加入互不相等的屬性:序號xu,即輸入結構體的順序。
在cmp函數中加入第三級關鍵字xu。很簡單的避免了不穩定的狀況。spa
struct g { int l; int w; int xu; bool tag; }sticks[5000]; int cmp(const void *a,const void *b) { struct g *c=(g *)a; struct g *d=(g *)b; if(c->l!=d->l) return c->l-d->l; else if(c->w!=d->w) return c->w-d->w; else return c->xu-d->xu; }
若是在排序後再進行穩定化處理,無疑要麻煩不少。調試