알고리즘/프로그래머스

프로그래머스 우박수열 정적분 c++

이영재의오른발 2022. 11. 29. 14:40
반응형
#include <string>
#include <vector>
#include <iostream>
using namespace std;

vector<double> collatz(int k) {
    int tmp = k;
    vector<double> rem;
    rem.push_back(tmp);
    
    while(1) {
        if(tmp % 2 == 0) {
            tmp = tmp / 2;
        }
        else {
            tmp = tmp * 3 + 1;
        }
        rem.push_back(tmp);
        if(tmp == 1) { break; }
    }
    return rem;
}

double di(double x1, double x2, vector<pair<double,double>> graph) {
    double sum = 0;
    for(int i=x1; i<x2; i++) {
        if(graph[i].second < graph[i+1].second) {
            double tmp;
            sum += graph[i].second;
            tmp = (graph[i+1].second - graph[i].second) / 2;
            sum += tmp;
        }
        else {
            sum += graph[i+1].second;
            double tmp = (graph[i].second - graph[i+1].second) / 2;
            sum += tmp;
        }
    }
    cout << endl;
    return sum;
}

vector<double> solution(int k, vector<vector<int>> ranges) {
    vector<double> answer;
    vector<pair<double,double>> graph;
        
    // 직사각형 + 직각삼각형
    vector<double> dot = collatz(k);
    
    // 최대 x 범위
    int maxLength = dot.size() - 1;
    
    for(int i=0; i<dot.size(); i++) {
        graph.push_back({i,dot[i]});
    }
    
    for(int i=0; i<ranges.size(); i++) {
        double x1,x2;
        x1 = ranges[i][0];
        x2 = maxLength + ranges[i][1];
        if(x1 > x2) { answer.push_back(-1.0); }
        else if(x1 == x2) { answer.push_back(0.0); }
        else {
            answer.push_back(di(x1,x2,graph));
        }
    }
    
    return answer;
}

https://www.youtube.com/watch?v=aJck__VUus4 

단편 영화를 보고나서 지적허영심을 채우고 싶어 풀어본 문제 

그래프와 콜라츠추측이 있어 생긴건 어렵게 생겼지만 막상 풀어보면 그닥 어렵지않다.

 

**

기능구현 목록 

 

1. 콜라츠추측 과정을 모두 벡터에 저장 기능

2. 구간에 따른 넓이 계산 기능

**

 

728x90
반응형