程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> poj 2376 貪心 區間覆蓋問題

poj 2376 貪心 區間覆蓋問題

編輯:關於C++

題意:

給n個區間 選擇盡量少的區間 覆蓋1~T這個區間

如果不能覆蓋 輸出-1

思路:

經典貪心 區間覆蓋

將所有區間按照起點從小到大排序 取終點在最右邊的那個區間

code:

 

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;

#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define mem(a, b) memset(a, b, sizeof(a))
typedef pair pii;
typedef long long LL;
//------------------------------
const int maxn = 25005;

int n, T;
struct node{
    int s,e;
    bool operator < (const node nt) const{
        return s < nt.s;
    }
}cow[maxn];
void init(){
    for(int i = 0; i < n; i++){
        scanf("%d%d",&cow[i].s,&cow[i].e);
    }
    sort(cow, cow + n);
}
void solve(){
    if(cow[0].s > 1){
        printf("-1\n");
        return;
    }

    int start_ = 1, end_ = 1, cnt = 1;
    for(int i = 0; i < n; i++){
        if(cow[i].s <= start_)
            end_ = max(end_, cow[i].e);
        else{
            cnt++;
            start_ = end_ + 1;
            if(cow[i].s <= start_) end_ = max(end_, cow[i].e);
            else{printf("-1\n"); return; }
        }
        if(end_ >= T) break;
    }
    if(end_ >= T)
        printf("%d\n",cnt);
    else printf("-1\n");
}
int main(){
    scanf("%d%d",&n,&T);
    init();
    solve();
    return 0;
}

竟錯了一次T_T 因為solve函數中最後少判斷了一個條件 end >= T......sigh...

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved