코딩테스트/백준

[백준][C++]13251번 조약돌 꺼내기

윤깡패 2023. 10. 10. 10:46

문제

https://www.acmicpc.net/problem/13251

 

13251번: 조약돌 꺼내기

첫째 줄에 뽑은 조약돌이 모두 같은 색일 확률을 출력한다. 정답과의 절대/상대 오차는 10-9까지 허용한다.

www.acmicpc.net

 

 

풀이

조합(Combination) 알고리즘

 

조합(Combination) 알고리즘

순열과 조합 핵심 이론 순열(Permutation) : 서로 다른 n개의 숫자에서 r개를 선택하여 순서를 고려해 나열할 경우의 수 (순서 고려 O) 조합(Combination) : 서로 다른 n개의 숫자에서 서로 다른 r개를 선택

soobin0821.tistory.com

 

 

코드

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

int main()
{
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);

  int M, N = 0, K;
  cin >> M;

  vector<int> count(M + 1);
  for(int i = 0; i < M; i++)
  {
    cin >> count[i];	// 각 조약돌 개수 저장하기
    N += count[i];	// 조약돌의 개수 더하기
  }

  cin >> K;

  double result = 0.0;
  for(int m = 0; m < M; m++)
  {
    double percent = 1.0;
    if(count[m] >= K)	// 선택 조약돌 개수보다 현재 색 조약돌 개수가 적으면 모두 같은 색으로 뽑힐 확률은 0
    {
      for(int i = 0; i < K; i++)
      {
        percent *= (double)(count[m] - i) / (N - i);
      }
      result += percent;	// 정답에 현재 색깔을 모두 뽑을 확률 더하기
    }
  }

  cout.precision(9);	// 오차 범위 내 출력을 위한 소수점 자릿수 설정
  cout << result;	// 정답 출력하기

  return 0;
}

 

 

오답

  • 한 색깔의 조약돌만 뽑을 확률을 색깔별로 모두 구한다.
    • 선택 조약돌 개수보다 현재 색 조약돌 개수가 적으면 모두 같은 색으로 뽑을 확률은 0

 

더보기
#include <iostream>
using namespace std;

static int M, K, T;
static int D[51];
static double probability[51];
static double ans = 0.0;

int main() 
{
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);

  cin >> M;

  for(int i = 0; i < M; i++)
  {
    cin >> D[i];
    T += D[i];
  }

  cin >> K;

  for(int i = 0; i < M; i++)
  {
    if(D[i] >= K)
    {
      probability[i] = 1.0;

      for(int k = 0; k < K; k++)
      {
        probability[i] *= (double)(D[i] - k) / (T - k);
      }
    }
    ans += probability[i];
  }

  cout << fixed;
  cout.precision(9);  // 오차 범위 내 출력을 위한 소수점 자릿수 설정
  cout << ans;
}

 

 

 

 

 

728x90