[백준 7281] Internetas (C#, C++) - soo:bak
작성일 :
문제 링크
설명
시간 순으로 n번 인터넷 연결 여부를 측정한 결과가 주어질 때, 가능한 최대 끊김 시간을 구하는 문제입니다.
측정 사이에 상태가 어떻게 변했는지는 모르므로, 연결이 있었던 시각들 사이의 시간 간격 중 최댓값이 가능한 최대 끊김 시간이 됩니다.
접근법
연결이 있었던 시각들만 모아 인접한 두 시각의 차이를 계산합니다. 입력을 순회하며 연결된 경우에만 이전 연결 시각과의 차이를 구해 최댓값을 갱신합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
class Program {
static void Main() {
var n = int.Parse(Console.ReadLine()!);
var maxGap = 0;
var prev = -1;
for (var i = 0; i < n; i++) {
var parts = Console.ReadLine()!.Split();
var t = int.Parse(parts[0]);
var m = int.Parse(parts[1]);
if (m == 1) {
if (prev != -1)
maxGap = Math.Max(maxGap, t - prev);
prev = t;
}
}
Console.WriteLine(maxGap);
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
int maxGap = 0;
int prev = -1;
for (int i = 0; i < n; i++) {
int t, m; cin >> t >> m;
if (m == 1) {
if (prev != -1)
maxGap = max(maxGap, t - prev);
prev = t;
}
}
cout << maxGap << "\n";
return 0;
}