Codeforces Round #306 (Div. 2) B,

來源:互聯網
上載者:User

Codeforces Round #306 (Div. 2) B,
題意

給一個長度為n的數組(n<=15)。
從中選出至少兩個數,要求滿足:
①最大和最小的差不能少於x
②選出的所有數的和在l和r之間

思路

n太小了。sort一下,然後直接枚舉最小和最大值,接著dfs中間剩下的即可,發現一個可行的就cnt++。
注意dfs中使用一個狀態參數來說明是否考慮sum的檢測,從而避免了used數組。

代碼
#include <cstdio>#include <algorithm>#include <cstring>using namespace std;const int maxn = 16;int s[maxn];int n;int mi,ma,x;int cnt = 0;void dfs(int st,int t,int sum,int k){    //k=0表示考慮當前的sum    //k=1表示不考慮當前的sum 因為之前已經考慮過它了    if(!k && mi<=sum && sum<=ma) cnt++;    if(st > t) return;    dfs(st+1,t,sum+s[st],0);    dfs(st+1,t,sum,1);}int main(){    scanf("%d",&n);    scanf("%d%d%d",&mi,&ma,&x);    for(int i = 0 ; i < n ; i ++) scanf("%d",&s[i]);    sort(s,s+n);    for(int i = 0 ; i < n-1 ; i ++) {        for(int j = i+1 ; j < n ; j ++) {            if(s[j]-s[i] < x || s[i]+s[j] > ma) continue;            if(j == i+1) {                if(s[i]+s[j] >= mi) {                    //printf("Hello");                    cnt ++;                }                continue;            }            dfs(i+1,j-1,s[i]+s[j],0);        }    }    printf("%d\n",cnt);    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.