programming challenges 2012 freckles - andstudy/forge GitHub Wiki

์ตœ์„ฑ๊ธฐ

  • Accepted :)

์†Œ์Šค์ฝ”๋“œ

#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <math.h>

using namespace std;

struct Vertex
{
	float x;
	float y;
	float minVal;
	bool inTree;

	void Init( float x_, float y_ )
	{
		x = x_;
		y = y_;
		//minVal = 
		inTree = false;
	}
};

class Main
{
public:
	Main( istream& stm ) : m_stmIn( stm ) {}
	void Solve();

	void Prim();

protected:
	void Init();
	float GetDistance( int a, int b );

	//------------------------------------------------------------------------

	istream&    m_stmIn;			// ํŒŒ์ผ์ž…๋ ฅ or STDIN ์ž…๋ ฅ.

	enum { MAX_VERTEX = 100 };
	Vertex		vertex[MAX_VERTEX];
	int			m_numVertex;
	float		m_result;


};

void Main::Init()
{
	m_numVertex = 0;
	m_result = 0.f;
}


void Main::Solve()
{
    int caseNum;

    m_stmIn >> caseNum;
	m_stmIn.get();

    for( int i = 0; i < caseNum; i++ )
    {
        Init();

        m_stmIn.get();
        m_stmIn >> m_numVertex;
        m_stmIn.get();

		for( int j = 0; j < m_numVertex; j++ )
        {
            float x, y;
            m_stmIn >> x >> y;
            m_stmIn.get();

			vertex[j].Init( x, y );
        }

		// solve.
		Prim();

		if( i > 0 )
			cout << endl;

		cout << fixed << showpoint << setprecision(2) << m_result << endl;
    }
}

float Main::GetDistance( int a, int b )
{
	return sqrt( pow(vertex[a].x - vertex[b].x,2) + pow(vertex[a].y - vertex[b].y,2) );
}

void Main::Prim()
{
	// 0๋ฒˆ ๋ฒ„ํ…์Šค๋ฅผ ์‹œ์ž‘์ ์œผ๋กœ ์žก๊ณ , ๋ชจ๋“  ๋‹ค๋ฅธ ๋ฒ„ํ…์Šค์˜ ๊ฑฐ๋ฆฌ๋ฅผ ์‹œ์ž‘์ ๊ณผ์˜ ๊ฑฐ๋ฆฌ๋กœ ์ดˆ๊ธฐํ™”.
	vertex[0].inTree = true;
	for( int i = 1; i < m_numVertex; i++ )
	{
		vertex[i].minVal = GetDistance( 0, i );
	}

	// 0๋ฒˆ์„ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ์ ๋“ค์˜ ์ˆ˜๋งŒํผ loop. ๋ณ€์ˆ˜ i๋Š” ์ฐธ์กฐ๋˜์ง€ ์•Š์Œ.
	for( int i = 0; i < m_numVertex - 1; i++ )
	{
		int idxNext = -1;						// ๋‹ค์Œ์œผ๋กœ tree์— ์ง‘์–ด๋„ฃ์„ ๋ฒ„ํ…์Šค๋ฅผ ์ฐพ๋Š”๋‹ค.
		for( int j = 0; j < m_numVertex; j++ )	// ๋ชจ๋“  ๋ฒ„ํ…์Šค ์ˆ˜๋งŒํผ loop.
		{
			if( vertex[j].inTree )				// ์ด๋ฏธ tree์— ์†ํ•œ ์ ์ด๋ฉด ํ†ต๊ณผ.
				continue;

			if( idxNext == -1 || vertex[idxNext].minVal > vertex[j].minVal )
				idxNext = j;
		}

		m_result += vertex[idxNext].minVal;
		vertex[idxNext].inTree = true;

		// ํ˜„์žฌ ๊ณ„์‚ฐ๋œ ๊ฑฐ๋ฆฌ๋ณด๋‹ค ์ƒˆ๋กœ ์ถ”๊ฐ€๋œ ๋ฒ„ํ…์Šค์™€์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ๋” ์งง์€ ๊ฒƒ์ด ์žˆ๋‹ค๋ฉด ๊ฐฑ์‹ .
		for( int j = 0; j < m_numVertex; j++ )
		{
			if( vertex[j].inTree )
				continue;

			float dist = GetDistance( idxNext, j );
			if( vertex[j].minVal > dist )
				vertex[j].minVal = dist;
		}

	}
}


int main( int argc, char* argv[] )
{
	if( argc > 1 ) // ๋ช…๋ นํ–‰ ์ธ์ž๋ฅผ ๋ฐ›๋Š”๋‹ค๋ฉด ํ•ด๋‹น ์ด๋ฆ„์˜ ํŒŒ์ผ์„ ์ธํ’‹์œผ๋กœ ์‚ผ๋Š”๋‹ค.
	{
		ifstream fstm( argv[1] );
		Main g( fstm );
		g.Solve();
	}
	else // ๊ทธ๋ƒฅ ์‹คํ–‰ํ•˜๋ฉด ํ‘œ์ค€์ž…๋ ฅ์œผ๋กœ ์ธํ’‹์„ ๋ฐ›์Œ.
	{
		Main g( cin );
		g.Solve();
	}

	return 0;
}
โš ๏ธ **GitHub.com Fallback** โš ๏ธ