ZeroJudge B526: 先別管這個了,你聽過微鼓勵嗎?

題目敘述

每筆測資第一行有一個正整數N,代表有N個人站成一排。第二行有一個正整數M,接下來會有M行,每行有兩個正整數a和b,代表要對a到b的人進行微鼓勵,被微鼓勵時如果目前是站著的人對坐下、坐下的人會站著,預設所有人一開始都是站著的。要求輸出在進行完所有微鼓勵後有幾個人是站著的。


範例輸入 #1

5

3

1 3

3 5

1 5

範例輸出 #1

4


解題思路

使用Map來存每一次微鼓勵的範圍,因為只要微鼓勵兩次就會變成站著等於沒有微鼓勵。將b+1之後就可以知道b-a是被微鼓勵的人數,將a和b放到Map中,如果已經有資料了就代表有重複微鼓勵的情況,所以將已經出現過的Map值做刪除,然後沒有存過的資料存到Map中。最後將Map轉換為Vector<Pair<int, int>>然後兩兩一組進行b-a的動作並將答案相加即可。

解題程式碼如下 (僅供參考):

#include <iostream>
#include <map>
#include <vector>
using namespace std;

map<int, int>MAP;

void change(int N)
{
    if (MAP[N] == 0)
    {
        MAP[N]++;
        return;
    }
    MAP.erase(N);
}

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    int N, M;
    cin >> N >> M;
    for (int i = 0; i<M; i++)
    {
        int a, b;
        cin >> a >> b;
        b++;
        change(a);
        change(b);
    }
    vector<pair<int, int>>ans;
    copy(MAP.begin(), MAP.end(), back_inserter(ans));
    int sum = 0;
    for (int i = 0; i<ans.size(); i++)
    {
        sum += ans[i+1].first - ans[i].first;
        i++;
    }
    cout << N-sum << "\n";
}

留言

這個網誌中的熱門文章

ZeroJudge M933: 邏輯電路

ZeroJudge A148: You Cannot Pass?!

ZeroJudge A263: 日期差幾天