๐
2025-10-21
๋ฌธ์ ๋งํฌ
๋ฌธ์ ์ค๋ช
์ด๋ ๊ณต์ ๋์ดํฐ์๋ ์์๊ฐ ํ๋ ์ค์น๋์ด ์์ต๋๋ค. ์ด ์์๋ ์ค์ฌ์ผ๋ก๋ถํฐ 2(m), 3(m), 4(m) ๊ฑฐ๋ฆฌ์ ์ง์ ์ ์ข์์ด ํ๋์ฉ ์์ต๋๋ค.
์ด ์์๋ฅผ ๋ ๋ช
์ด ๋ง์ฃผ ๋ณด๊ณ ํ๋ค๊ณ ํ ๋, ์์๊ฐ ํํ์ธ ์ํ์์ ๊ฐ๊ฐ์ ์ํด ์์์ ๊ฑธ๋ฆฌ๋ ํ ํฌ์ ํฌ๊ธฐ๊ฐ ์๋ก ์์๋์ด ์์ ํ ๊ท ํ์ ์ด๋ฃฐ ์ ์๋ค๋ฉด ๊ทธ ๋ ์ฌ๋์ ์์ ์ง๊ฟ์ด๋ผ๊ณ ํฉ๋๋ค. ์ฆ, ํ์นํ ์ฌ๋์ ๋ฌด๊ฒ์ ์์ ์ถ๊ณผ ์ข์ ๊ฐ์ ๊ฑฐ๋ฆฌ์ ๊ณฑ์ด ์์ชฝ ๋ค ๊ฐ๋ค๋ฉด ์์ ์ง๊ฟ์ด๋ผ๊ณ ํ ์ ์์ต๋๋ค.
์ฌ๋๋ค์ ๋ชธ๋ฌด๊ฒ ๋ชฉ๋ก weights์ด ์ฃผ์ด์ง ๋, ์์ ์ง๊ฟ์ด ๋ช ์ ์กด์ฌํ๋์ง ๊ตฌํ์ฌ return ํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
์ ํ ์ฌํญ
๋ชจ๋ ์์ ๊ณ์ฐํ์ฌ ์๊ฐ๋ณต์ก๋๊ฐ O(N^2)์ผ๋ก ์๊ฐ ์ด๊ณผ๊ฐ ๋๋ค.
#include <vector>
using namespace std;
long long solution(vector<int> weights) {
long long answer = 0;
vector<int> seesaw = {2,3,4};
int idx = 0;
while(idx<weights.size())
{
int temp = weights[idx];
for(int i = idx + 1; i < weights.size(); i++)
{
if(temp == weights[i])
{
answer += 1;
continue;
}
for(const int& dist1 : seesaw)
{
for(const int& dist2 : seesaw)
{
if(temp*dist1%dist2 != 0) continue;
if(temp*dist1/dist2 < weights[i]) break;
if(temp*dist1/dist2 == weights[i])
{
answer += 1;
break;
}
}
}
}
idx += 1;
}
return answer;
}
๋ชธ๋ฌด๊ฒ๊ฐ ๊ฐ์ ๊ฒฝ์ฐ์ ์กฐํฉ ์๋ฅผ ๋จผ์ ๊ณ์ฐ ํ ๋ชธ๋ฌด๊ฒ ๋ณ๋ก ๊ฑฐ๋ฆฌ์ ๋ฐ๋ฅธ ์กฐํฉ ๊ณ์ฐํ์ฌ ์๊ฐ๋ณต์ก๋๋ฅผ O(N)์ผ๋ก ์ค์๋ค.
#include <vector>
#include <unordered_map>
using namespace std;
long long solution(vector<int> weights) {
long long answer = 0;
unordered_map<int, long long> weightCount;
// ๋ชธ๋ฌด๊ฒ๋ณ ์ธ์ ์
for(const int& i : weights)
{
weightCount[i] += 1;
}
// ๊ฐ์ ๋ชธ๋ฌด๊ฒ ์กฐํฉ ์
for(const auto& [w,c] : weightCount)
{
if(c>1)
{
answer+=c*(c-1)/2;
}
}
for(const auto& [w,c] : weightCount)
{
// 2:3
if(w * 2 % 3 == 0)
{
int temp = w * 2 / 3;
if(weightCount.find(temp) != weightCount.end())
{
answer += c * weightCount[temp];
}
}
// 2:4
if(w * 2 % 4 == 0)
{
int temp = w * 2 / 4;
if(weightCount.find(temp) != weightCount.end())
{
answer += c * weightCount[temp];
}
}
// 3:4
if(w * 3 % 4 == 0)
{
int temp = w * 3 / 4;
if(weightCount.find(temp) != weightCount.end())
{
answer += c * weightCount[temp];
}
}
}
return answer;
}
์ถ์ฒ ํ๋ก๊ทธ๋๋จธ์ค: ์์ ์ง๊ฟ