【hoj】2608 assemble 二分法

來源:互聯網
上載者:User

標籤:二分尋找   hoj   

 
/* 思路:本文要求找到滿足預算的最好配置的組件,組裝電腦,所以可以是按照*電腦的quantity以標準去尋找相應的組件,就可以應用二分法,將每一種組件中的類型都按照品質排序*選擇滿足整體品質的要求的情況下的最低價格*/#include<iostream>#include<string>#include<string.h>#include<algorithm>#include<cstdio>#include<cstring>#define MAX 1010using namespace std;int budge;int num,m;struct compnent{    char type[25];    char name[25];    int quatity;    int price;};struct compnent com[MAX];int kind[MAX];bool cmp( compnent a,compnent b){    return (strcmp(a.type,b.type) < 0)||((strcmp(a.type,b.type)==0) && (a.quatity < b.quatity));}bool judge(int mid){    int b = 0,min;    for(int i = 0;i < m-1;i++){        min = 0x3f3f3f3f;        for(int j = kind[i];j < kind[i+1];j++){            if(com[j].quatity >= mid){//在每一類中找到品質大於或者等於MID的型號,選擇價格較低的                min = (com[j].price < min)?com[j].price:min;            }        }        if(min == 0x3f3f3f3f)//如果為此值那麼表示該類別中的品質都小於mid 因為min 是一個超大值            return false;        b += min;        cout<<min<<endl;    }    if(b <= budge)//低於預算,則這樣的品質可以接受,試著尋找更高品質的        return true;    else//高出預算,不行找更低品質的        return false;}int main(){    int n,max,min;    cin>>n;    while(n--){        cin>>num>>budge;        max = 0;        min = 0x3f3f3f3f;        for(int i = 0;i < num;i++){            cin>>com[i].type>>com[i].name>>com[i].price>>com[i].quatity;//通過品質大小尋找所以先找到最大和最小的值            max = (com[i].quatity > max) ? com[i].quatity : max;            min = (com[i].quatity < min) ? com[i].quatity : min;        }        sort(com,com+num,cmp);//將所有輸入同一類的按照品質的大小排序        memset(kind,0,sizeof(kind));        m = 1;        for(int i = 1;i < num;i++){//頭為0不用再設定            if(strcmp(com[i].type,com[i-1].type))//找到每一類的起始位置也就是前一類的終止位置                kind[m++] = i;        }        kind[m++] = num;//用於界定第num-1號類型的數量        int high = max,low = min,mid,res = 0;        //品質與價格不成正比,行嗎?        while(low <= high){//通過品質進行二分尋找            mid = (low+high)/2;            if(judge(mid)){                res = mid;                low = mid+1;                cout<<"res "<<res<<' '<<mid<<endl;            }            else{                high = mid-1;            }        }        cout<<res<<endl;    }    return 0;}

相關關鍵詞:
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.