【題解】ZeroJudge e796: p3. 站牌廣告

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=e796
【解題想法】

  • (Line-22) 若有多個則輸出編號最大者。
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

int ppl[1005];

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int B, P, x, y;
    cin >> B >> P;
    for (int i=0; i<P; i++){
        cin >> x >> y;
        if (y < x) swap(x, y);
        for (int j=x; j<=y; j++)
            ppl[j]++;
    }
    int mn = 1e9, idx_mn = -1;
    int mx = 0, idx_mx = -1;
    for (int i=1; i<=B; i++){
        if (ppl[i] >= mx) {
            mx = ppl[i];
            idx_mx = i;
        }
        if (ppl[i] < mn) {
            mn = ppl[i];
            idx_mn = i;
        }
    }
    cout << idx_mn << ' ' << idx_mx << '\n';
    return 0;
}

Python code (credit: Amy Chou)
⚠️注意:實際測資與範例格式不同,B、P分成兩行輸入。

B = int(input())
P = int(input())
ppl = [0 for _ in range(B+1)]
for _ in range(P):
    x, y = map(int, input().split())
    if y < x:
        x, y = y, x
    for j in range(x, y+1):
        ppl[j] += 1

mn = 1000000
mx = 0
idx_mx = -1
idx_mn = -1
for i in range(1, B+1):
    if ppl[i] >= mx:
        mx = ppl[i]
        idx_mx = i
    if ppl[i] < mn:
        mn = ppl[i]
        idx_mn = i

print(idx_mn, idx_mx)

分享本文 Share with friends