公式

B - 噂の広がり / Spread of Rumors 解説 by kyopro_friends


\(N\) 人の生徒それぞれが噂を知っているかどうかを表す真偽値の配列を用意し、グループワークが行われるごとに順にこの情報を更新すればよいです。

実装例 (C++)

#include<bits/stdc++.h>
using namespace std;

int main(){
  int n, m, k;
  cin >> n >> m >> k;
  vector<bool> status(n);
  for(int i=0; i<k; i++) status[i] = true;

  for(int i=0; i<m; i++){
    int a, b;
    cin >> a >> b;
    a--, b--;
    if(status[a] || status[b]){
      status[a] = true;
      status[b] = true;
    }
  }

  int ans = 0;
  for(int i=0; i<n; i++){
    if(status[i]) ans++;
  }
  cout << ans << endl;
}

実装例 (Python)

N, M, K = map(int, input().split())
status = [False] * N
for i in range(K):
  status[i] = True

for _ in range(M):
  a, b = map(int, input().split())
  a -= 1
  b -= 1
  if status[a] or status[b]:
    status[a] = True
    status[b] = True

ans = 0
for i in range(N):
  if status[i]:
    ans += 1

print(ans)

投稿日時:
最終更新: