HDOJ 1050 Moving Tables 【貪心】

HDOJ 1050 Moving Tables 【貪心】

題目鏈接 http://acm.hdu.edu.cn/showproblem.php?pid=1050


這個題是根據貪心訓練所以寫的貪心
但是有一種更簡單的求法就是求最大重複區間:
【將走廊分成200塊,每次輸入後就對涉及到的走廊+1
最後輸出這些數組裏最大的數*10就可以了】
上面這種寫法比較簡單,不貼代碼了


貪心的話首先是把輸入的區間預處理:
1、左區間小於右區間,不符合的話交換一下
2、左邊的數據是偶數的話就-1換成奇數
3、右邊的數據是奇數的話就+1換成偶數
以上操作是將涉及到的區間擴展到最大邊界
然後貪心一直跑
每跑一趟就將可以同時進行的操作標記爲vis,同時num++
然後再從頭開始將沒有訪問過的區間標記vis,num++
最後所有的區間都訪問過後,輸出最後的num*10即可


這個題一開始區間排序是按右區間從小到大,再左區間從小到大排
然而總是wa……
換成先按左區間從小到大排再按右區間從小到大就過了……
反例見下:
1
19
75 154
125 158
176 48
196 65
21 171
15 170
17 100
61 116
3 189
98 104
112 19
163 66
42 14
81 168
53 165
36 143
84 140
105 199
195 151
AC代碼結果爲150,WA代碼結果爲160
**按照右房間排序後,右房間的號碼一旦大於之後所有的左房間號碼,
那麼之後的所有區間就是每個區間佔用一個新的num
**按照左房間排序,右房間號碼過大後,下一個區間右房間依然可能變小,所以每次機會都是均等的,可以進行貪心
所以……要那麼排……就素醬紫……


#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
typedef struct point{
    int x, y;
    int vis;
    bool operator < (const point& p) const{
        if(x == p.x) return y < p.y;
        else return x < p.x;
    }
    bool operator > (const point& p) const{
        return p < *this;
    }
}p;
int T, N;
p room[205];
int End, num, cnt;

int main(){
    scanf("%d", &T);
    while(T--){
        scanf("%d", &N);
        for(int i = 0; i < N; i++) scanf("%d%d", &room[i].x, &room[i].y);
        for(int i = 0; i < N; i++){
            room[i].vis = false;
            if(room[i].x > room[i].y) swap(room[i].x, room[i].y);
            if(!(room[i].x & 1)) room[i].x -= 1;
            if(room[i].y & 1) room[i].y += 1;
        }
        sort(room, room+N);
        //for(int i = 0; i < N; i++) printf("%d\t%d\n", room[i].x, room[i].y);
        cnt = 0;
        num = 0;
        while(cnt != N){
            for(int i = 0; i < N; i++){
                if(room[i].vis == 0){
                    End = room[i].y;
                    room[i].vis = true;
                    cnt++;
                    num++;
                    break;
                }
            }
            for(int i = 1; i < N; i++){
                if(room[i].x >= End && room[i].vis == false){
                    End = room[i].y;
                    cnt++;
                    room[i].vis = true;
                }
            }
        }
        printf("%d\n", num*10);
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章