Skip to content

algorithm problem 15

Jongbin Oh edited this page Jun 8, 2013 · 1 revision

문제 15번 경시대회 점수판 (Contest Scoreboard)

  • 책 입력부분에 대한 한글 번역이 너무 애매모호해서 찾아봤는데.

  • 역시 번역이 이상한거였네요.

      contestant, problem, time, L
      
      Sample Input:
      1
      
      1 2 10 I
      3 1 11 C
      1 2 19 R
      1 2 21 C
      1 1 25 C
    
  • 영문 Contest Scoreboard


  1. 한 문제도 풀지 못한 팀도 출력이 되어야 하나요?
  • 출력안해도 될것 같습니다. (display only the contestants that have made a submission.)
  • 역시 이것도 잘못생각. 맞추건 못맞추건 결과를 submission 한 팀은 출력해야할듯 합니다.
  1. 첫번째 문제는 풀고 두번째 문제는 I만 두번에 결국 못 풀었다면 이 팀의 벌점은?
  • 두번째 문제 벌점 40점이 최종 결과에 추가가 되느냐 아니냐 그것이 문제로세...

  • 추가가 안 될듯 하다. 다 푼줄 알았더니 한참 남았군.. 흑..

    • 일단 1문제는 풀었으니 출력은 해야하므로 첫번째문제에서 걸린 시간+40점의 벌점이 출력될듯 합니다.
  • (Each line of output will contain a contestant number, the number of problems solved by the contestant and the time penalty accumulated by the contestant)

  • 헉. 문제를 다시 읽어보니 아니네요 ... Correct 한 문제가 1개 이상일때만 출력하는줄 알았는데. 풀지못했어도 제출만 해도 submission 만 해도 출력하는거였네요. I 일경우 나중에 Correct 했을때만 최종벌점시간에 적용하고 .....너무 늦어서 수정은 내일

Java 버전

  • TDD 가 쉽지 않네요. Test case 작성은 프로그램 작성후 해버렸습니다 아악

    • Test Driven을 고집할 필요는 없습니다.
    • Test Accelerated Development (["TAD"])로 하시면 됩니다.
  • submission 하면 출력해주고 C 일때만 I 의 시간벌점을 계산하도록 수정해보았습니다.

ScoreBoardMain.java

    import java.io.*;
    import java.util.*;
    
    public class ScoreBoardMain
    {	
    	ArrayList<Contestant> ctList = new ArrayList<Contestant>();
    	
    	public static void main(String[] args)
    	{
    	
    		ScoreBoardMain sbMain = new ScoreBoardMain();
    		
    		int testCase = Integer.parseInt(ReadLine());
    		ReadLine();
    		
    		/* testCase 만큼 */
    		while(testCase != 0)
    		{
    			sbMain.InitScoreBoard();
    			sbMain.RunScoreBoard();
    			sbMain.PrintScoreBoard();
    			
    			testCase--;
    		}
    		
    	}
    	
    	public void InitScoreBoard()
    	{
    		ctList.clear();
    	}
    	
    	/* 빈칸이 들어올때까지 점수판 Parse */
    	public void RunScoreBoard()
    	{
    		String in;
    		while( (in = ReadLine()) != null )
    		{
    			if( in.equals("") )
    				break;
    			
    			ParseInputData(in);
    		}				
    	}
    	
    	public void PrintScoreBoard()
    	{
    		for(int i=0; i<ctList.size(); i++)
    		{
    			System.out.println(ctList.get(i).GetTeamNum() + " "
    					+ ctList.get(i).GetSolvedProblemCount() + " "
    					+ ctList.get(i).GetTotalPenaltyTime());
    		}
    	}
    	
    	/* teamNum, problemNum, time, L type 파싱 */
    	public void ParseInputData(String in)
    	{
    		String[] token = new String[5];
    		token = in.split(" ");
    		
    		// L type 에 상관없이 무조건 contestant 추가
    		Contestant cont = GetExistContestant(token[0]);
    		
    		if( cont == null )
    		{
    			cont = new Contestant(token[0]);
    			ctList.add(cont);
    		}
    		
    		cont.SubmitProblem(token[1],token[2],token[3]);
    		
    	}
    	
    	/* ArrayList 에 존재하는 Contestant 인지 체크.. 다른방법은 없나 ㅜㅜ */
    	public Contestant GetExistContestant(String teamNum)
    	{
    		if( ctList.size() == 0)
    			return null;
    		
    		for(int i=0; i< ctList.size(); i++)
    		{
    			if(ctList.get(i).GetTeamNum() == Integer.parseInt(teamNum))
    				return ctList.get(i);
    		}
    		return null;
    	}
    	
    	public static String ReadLine()
    	{
    		String data = null;
    		
    		try
    		{
    			BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
    			data = is.readLine();
    		}
    		catch(IOException e)
    		{
    			System.out.println("IOException " +e);
    		}
    		
    		return data;		
    	}
    
    }

Contestant.java

    import java.util.*;
    
    public class Contestant 
    {
    	private int teamNum;
    	private int solvedProblemCount;
    	private int totalPenaltyTime;
    	
    	/* HashMap <팀번호,문제당벌점> */
    	HashMap<String,Integer> tScoreMap = new HashMap<String,Integer>();
    	
    	public Contestant(String teamNum)
    	{
    		this.teamNum = Integer.parseInt(teamNum);
    	}
    	
    	
    	public void SubmitProblem(String problemNumber,String time, String type)
    	{
    		totalPenaltyTime += ComputeTime(problemNumber,time,type);
    		
    	}
    	
    	// type 별로 Time 계산.
    	public int ComputeTime(String num, String time,String type)
    	{
    		int resultTime = 0;
    		
    		if( type.equals("C") )	// Correct
    		{
    			solvedProblemCount++;
    			
    			if(tScoreMap.get(num) != null)
    				resultTime += tScoreMap.get(num);
    
    			resultTime += Integer.parseInt(time); 
    		}
    		
    		if( type.equals("I") )	// Incorrect
    		{
    			if( tScoreMap.get(num) != null)
    				tScoreMap.put(num, tScoreMap.get(num) + 20);
    			else
    				tScoreMap.put(num,20);
    		}
    		
    		/* 나머지 3 case 는 처리 할게 없음.
    		if( type == "R" )	// clarification Request
    		if( type == "U" )	// Unjudged
    		if( type == "E" )	// Erroneous submission
    		*/
    			
    		return resultTime;
    		
    	}
    	
    	public int GetTeamNum()
    	{
    		return teamNum;
    	}
    	
    	public int GetSolvedProblemCount()
    	{
    		return solvedProblemCount;
    	}
    	
    	public int GetTotalPenaltyTime()
    	{
    		return totalPenaltyTime;
    	}	
    	
    }

ContestantTest.java

    import junit.framework.TestCase;
    
    
    public class ContestantTest extends TestCase 
    {
    
    	public void testSubmitProblem() 
    	{
    		
    		/* test 1 */
    		Contestant c1 = new Contestant("1");
    		c1.SubmitProblem("2","10","I");
    		assertEquals("1-1",c1.GetTotalPenaltyTime(),0);
    		c1.SubmitProblem("2","19","R");
    		assertEquals("1-3",c1.GetTotalPenaltyTime(),0);
    		c1.SubmitProblem("2","21","C");
    		assertEquals("1-4",c1.GetTotalPenaltyTime(),41);
    		c1.SubmitProblem("1","25","C");
    		assertEquals("1-5",c1.GetTotalPenaltyTime(),66);		
    
    		/* test 2 */
    		Contestant c2 = new Contestant("2");
    		c2.SubmitProblem("2","30","C");
    		assertEquals("2-1",c2.GetTotalPenaltyTime(),30);
    		c2.SubmitProblem("2","19","R");
    		assertEquals("2-2",c2.GetTotalPenaltyTime(),30);
    		c2.SubmitProblem("3","50","I");
    		assertEquals("2-3",c2.GetTotalPenaltyTime(),30);
    		c2.SubmitProblem("3","10","C");
    		assertEquals("2-4",c2.GetTotalPenaltyTime(),60);		
    
    		/* test 3 */
    		Contestant c3 = new Contestant("1");
    		c3.SubmitProblem("5","10","I");
    		assertEquals("3-1",c3.GetTotalPenaltyTime(),0);
    		c3.SubmitProblem("4","19","R");
    		assertEquals("3-2",c3.GetTotalPenaltyTime(),0);
    		c3.SubmitProblem("3","21","I");
    		assertEquals("3-3",c3.GetTotalPenaltyTime(),0);
    		c3.SubmitProblem("2","25","I");
    		assertEquals("3-4",c3.GetTotalPenaltyTime(),0);		
    
    	}
    
    	public void testComputeTime() 
    	{
    		Contestant c = new Contestant("1");
    		
    		assertEquals("1",c.ComputeTime("1","10","I"),0);
    		assertEquals("2",c.ComputeTime("2","10","I"),0);
    		assertEquals("3",c.ComputeTime("1","11","C"),31);
    		assertEquals("4",c.ComputeTime("1","19","R"),0);
    		assertEquals("5",c.ComputeTime("2","10","I"),0);		
    		assertEquals("6",c.ComputeTime("2","10","C"),50);
    	}
    
    }

ScoreBoardMainTest.java

    import junit.framework.TestCase;
    
    
    public class ScoreBoardMainTest extends TestCase 
    {
    	ScoreBoardMain sbMain = new ScoreBoardMain();
    	
    	
    	public void testRunScoreBoard() 
    	{
    
    	}
    
    	public void testParseInputData() 
    	{
    		/* test 1 */
    		sbMain.ParseInputData("1 2 10 I");
    		sbMain.ParseInputData("1 2 19 R");
    		sbMain.ParseInputData("1 2 21 C");
    		sbMain.ParseInputData("1 1 25 C");
    		assertEquals("1-1",sbMain.ctList.size(),1);
    		assertEquals("1-2",sbMain.ctList.get(0).GetTeamNum(),1);
    		assertEquals("1-3",sbMain.ctList.get(0).GetSolvedProblemCount(),2);
    		assertEquals("1-4",sbMain.ctList.get(0).GetTotalPenaltyTime(),66);
    		sbMain.ctList.clear();
    		
    		/* test 2 */
    		sbMain.ParseInputData("4 2 30 C");
    		sbMain.ParseInputData("1 2 19 R");
    		sbMain.ParseInputData("4 2 50 U");
    		sbMain.ParseInputData("4 5 25 E");
    		sbMain.ParseInputData("4 3 22 E");
    		assertEquals("2-1",sbMain.ctList.size(),2);
    		assertEquals("2-2",sbMain.ctList.get(0).GetTeamNum(),4);
    		assertEquals("2-3",sbMain.ctList.get(0).GetSolvedProblemCount(),1);
    		assertEquals("2-4",sbMain.ctList.get(0).GetTotalPenaltyTime(),30);
    		assertEquals("2-5",sbMain.ctList.get(1).GetTeamNum(),1);
    		assertEquals("2-6",sbMain.ctList.get(1).GetSolvedProblemCount(),0);
    		assertEquals("2-7",sbMain.ctList.get(1).GetTotalPenaltyTime(),0);
    		sbMain.ctList.clear();
    
    		/* test 3 */
    		sbMain.ParseInputData("5 3 20 I");
    		sbMain.ParseInputData("5 4 15 R");
    		sbMain.ParseInputData("5 4 30 I");
    		sbMain.ParseInputData("5 3 30 C");
    		assertEquals("3-1",sbMain.ctList.size(),1);
    		assertEquals("3-2",sbMain.ctList.get(0).GetTeamNum(),5);
    		assertEquals("3-3",sbMain.ctList.get(0).GetSolvedProblemCount(),1);
    		assertEquals("3-4",sbMain.ctList.get(0).GetTotalPenaltyTime(),50);
    		sbMain.ctList.clear();
    		
    	}
    
    	public void testGetExistContestant() 
    	{
    		Contestant c1 = new Contestant("1");
    		Contestant c2 = new Contestant("2");
    		Contestant c3 = new Contestant("3");
    		
    		sbMain.ctList.add(c1);
    		assertEquals("1",sbMain.GetExistContestant("1"),c1);
    		assertEquals("1",sbMain.GetExistContestant("2"),null);
    		
    		sbMain.ctList.add(c2);
    		sbMain.ctList.add(c3);
    		assertEquals("1",sbMain.GetExistContestant("5"),null);
    		assertEquals("1",sbMain.GetExistContestant("3"),c3);
    	}
    
    }

Study 결과

ScoreBoardMain.java

    import java.io.*;
    import java.util.*;
    
    public class ScoreBoardMain
    {	
    	ArrayList<Contestant> ctList = new ArrayList<Contestant>();
    	
    	public static void main(String[] args)
    	{
    	
    		ScoreBoardMain sbMain = new ScoreBoardMain();
    		
    		int testCase = Integer.parseInt(ReadLine());
    		ReadLine();
    		
    		/* testCase 만큼 */
    		while(testCase != 0)
    		{
    			sbMain.InitScoreBoard();
    			sbMain.RunScoreBoard();
    			sbMain.PrintScoreBoard();
    			
    			testCase--;
    		}
    		
    	}
    	
    	public void InitScoreBoard()
    	{
    		ctList.clear();
    	}
    	
    	/* 빈칸이 들어올때까지 점수판 Parse */
    	public void RunScoreBoard()
    	{
    		String in;
    		while( (in = ReadLine()) != null )
    		{
    			if( in.equals("") )
    				break;
    			
    			ParseInputData(in);
    		}				
    	}
    	
    	public void PrintScoreBoard()
    	{
    		for(Contestant cnt : ctList){
    			System.out.println(cnt);
    		}
    	}
    	
    	/* teamNum, problemNum, time, L type 파싱 */
    	public void ParseInputData(String in)
    	{
    		String[] token = new String[5];
    		token = in.split(" ");
    		
    		// L type 에 상관없이 무조건 contestant 추가
    		Contestant cont = GetExistContestant(token[0]);
    		
    		if( cont == null )
    		{
    			cont = new Contestant(token[0]);
    			ctList.add(cont);
    		}
    		
    		cont.SubmitProblem(token[1],token[2],token[3]);
    		
    	}
    	
    	/* ArrayList 에 존재하는 Contestant 인지 체크.. 다른방법은 없나 ㅜㅜ */
    	public Contestant GetExistContestant(String teamNum)
    	{
    		if( ctList.size() == 0)
    			return null;
    		
    		for(int i=0; i< ctList.size(); i++)
    		{
    			if(ctList.get(i).GetTeamNum() == Integer.parseInt(teamNum))
    				return ctList.get(i);
    		}
    		return null;
    	}
    	
    	public static String ReadLine()
    	{
    		String data = null;
    		
    		try
    		{
    			BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
    			data = is.readLine();
    		}
    		catch(IOException e)
    		{
    			System.out.println("IOException " +e);
    		}
    		
    		return data;		
    	}
    
    	public void SortDataInput() 
    	{
    		Contestant [] cnts = new Contestant[ctList.size()];
    		cnts = ctList.toArray(cnts);
    		 Arrays.sort(cnts);
    		ctList = new ArrayList<Contestant>();
    		for(Contestant row : cnts){
    			ctList.add(row);
    		}
    	}
    
    }

Contestant .java

    import java.util.*;
    
    public class Contestant implements Comparable<Contestant> 
    {
    	private int teamNum;
    	private int solvedProblemCount;
    	private int totalPenaltyTime;
    	
    	/* HashMap <팀번호,문제당벌점> */
    	HashMap<String,Integer> tScoreMap = new HashMap<String,Integer>();
    	
    	public Contestant(String teamNum)
    	{
    		this.teamNum = Integer.parseInt(teamNum);
    	}
    	
    	
    	public void SubmitProblem(String problemNumber,String time, String type)
    	{
    		totalPenaltyTime += ComputeTime(problemNumber,time,type);
    		
    	}
    	
    	// type 별로 Time 계산.
    	public int ComputeTime(String num, String time,String type)
    	{
    		int resultTime = 0;
    		
    		if( type.equals("C") )	// Correct
    		{
    			solvedProblemCount++;
    			
    			if(tScoreMap.get(num) != null)
    				resultTime += tScoreMap.get(num);
    
    			resultTime += Integer.parseInt(time); 
    		}
    		
    		if( type.equals("I") )	// Incorrect
    		{
    			if( tScoreMap.get(num) != null)
    				tScoreMap.put(num, tScoreMap.get(num) + 20);
    			else
    				tScoreMap.put(num,20);
    		}
    		
    		/* 나머지 3 case 는 처리 할게 없음.
    		if( type == "R" )	// clarification Request
    		if( type == "U" )	// Unjudged
    		if( type == "E" )	// Erroneous submission
    		*/
    			
    		return resultTime;
    		
    	}
    	
    	public int GetTeamNum()
    	{
    		return teamNum;
    	}
    	
    	public int GetSolvedProblemCount()
    	{
    		return solvedProblemCount;
    	}
    	
    	public int GetTotalPenaltyTime()
    	{
    		return totalPenaltyTime;
    	}
    
    
    	public int compareTo(Contestant o) {
    		if(this.solvedProblemCount > o.GetSolvedProblemCount())
    			return -1;
    		else if( this.solvedProblemCount < o.GetSolvedProblemCount())
    			return 1;
    		else if( this.totalPenaltyTime > o.GetTotalPenaltyTime())
    			return -1;
    		else if(this.totalPenaltyTime < o.GetTotalPenaltyTime())
    			return 1;
    		
    		return 0;
    	}	
    	public String toString(){
    		return teamNum + " " + solvedProblemCount + " " + totalPenaltyTime;
    	}
    	
    }

ScoreBoardMainTest.java

    import junit.framework.TestCase;
    
    
    public class ScoreBoardMainTest extends TestCase 
    {
    	ScoreBoardMain sbMain = new ScoreBoardMain();
    	
    	
    	public void testRunScoreBoard() 
    	{
    
    	}
    
    	public void testParseInputData() 
    	{
    		/* test 1 */
    		sbMain.ParseInputData("1 2 10 I");
    		sbMain.ParseInputData("1 2 19 R");
    		sbMain.ParseInputData("1 2 21 C");
    		sbMain.ParseInputData("1 1 25 C");
    		assertEquals("1-1",sbMain.ctList.size(),1);
    		assertEquals("1-2",sbMain.ctList.get(0).GetTeamNum(),1);
    		assertEquals("1-3",sbMain.ctList.get(0).GetSolvedProblemCount(),2);
    		assertEquals("1-4",sbMain.ctList.get(0).GetTotalPenaltyTime(),66);
    		sbMain.ctList.clear();
    		
    		/* test 2 */
    		sbMain.ParseInputData("4 2 30 C");
    		sbMain.ParseInputData("1 2 19 R");
    		sbMain.ParseInputData("4 2 50 U");
    		sbMain.ParseInputData("4 5 25 E");
    		sbMain.ParseInputData("4 3 22 E");
    		assertEquals("2-1",sbMain.ctList.size(),2);
    		assertEquals("2-2",sbMain.ctList.get(0).GetTeamNum(),4);
    		assertEquals("2-3",sbMain.ctList.get(0).GetSolvedProblemCount(),1);
    		assertEquals("2-4",sbMain.ctList.get(0).GetTotalPenaltyTime(),30);
    		assertEquals("2-5",sbMain.ctList.get(1).GetTeamNum(),1);
    		assertEquals("2-6",sbMain.ctList.get(1).GetSolvedProblemCount(),0);
    		assertEquals("2-7",sbMain.ctList.get(1).GetTotalPenaltyTime(),0);
    		sbMain.ctList.clear();
    
    		/* test 3 */
    		sbMain.ParseInputData("5 3 20 I");
    		sbMain.ParseInputData("5 4 15 R");
    		sbMain.ParseInputData("5 4 30 I");
    		sbMain.ParseInputData("5 3 30 C");
    		assertEquals("3-1",sbMain.ctList.size(),1);
    		assertEquals("3-2",sbMain.ctList.get(0).GetTeamNum(),5);
    		assertEquals("3-3",sbMain.ctList.get(0).GetSolvedProblemCount(),1);
    		assertEquals("3-4",sbMain.ctList.get(0).GetTotalPenaltyTime(),50);
    		sbMain.ctList.clear();
    		
    	}
    
    	public void testGetExistContestant() 
    	{
    		Contestant c1 = new Contestant("1");
    		Contestant c2 = new Contestant("2");
    		Contestant c3 = new Contestant("3");
    		
    		sbMain.ctList.add(c1);
    		assertEquals("1",sbMain.GetExistContestant("1"),c1);
    		assertEquals("1",sbMain.GetExistContestant("2"),null);
    		
    		sbMain.ctList.add(c2);
    		sbMain.ctList.add(c3);
    		assertEquals("1",sbMain.GetExistContestant("5"),null);
    		assertEquals("1",sbMain.GetExistContestant("3"),c3);
    	}
    	
             /* 정렬 */
    	public void testSortResult() 
    	{
    		/* test 1 */
    		sbMain.ParseInputData("1 2 10 I");
    		sbMain.ParseInputData("1 2 19 R");
    		sbMain.ParseInputData("1 2 21 C");
    		sbMain.ParseInputData("1 1 25 C");
    		sbMain.ParseInputData("4 2 30 C");
    		sbMain.ParseInputData("4 2 50 U");
    		sbMain.ParseInputData("4 5 25 C");
    		sbMain.ParseInputData("4 3 42 E");
    		sbMain.SortDataInput();
    		sbMain.PrintScoreBoard();
    		
    	}
    
    }

폭풍언덕

  • 아직 충분한 테스트를 한거 아니구요 출력결과만 제대로 나오나 확인했습니다. --;;
  • 3개의 클래스를 정의하여 프로그램을 구현했습니다.
  • Scoreboard 클래스 : 메인 클래스
  • ScoreRecord 클래스 : 입력 데이터 저장 클래스
  • Team 클래스 : 팀의 번호(아이디), 푼 문제와 걸린 시간을 저장한 클래스

Scoreboard.java

    import java.util.*;
    import java.io.*;
    
    public class Scoreboard {
    	public static void main(String args[]) throws IOException
    	{
    		// Map<팀번호, 팀 객체>
    		TreeMap<Integer, Team> teams;  
    		
    		// 케이스 갯수  입력
    		String line = readLine();
    		int count = Integer.parseInt(line);
    		if (count <= 0)
    		{
    			System.out.println("Error: invalid number!!");
    			return;
    		}
    
    		// 공백라인 입력
    		line = readLine();
    		if (line.length() > 0)
    		{
    			System.out.println("Error: must be a blank line");
    			return;
    		}
    		
    		// 케이스 수만큼 루프
    		while (count > 0)	
    		{
    			// Map<팀번호, 팀객체> 초기화
    			teams = new TreeMap<Integer, Team>();
    			
    			// 데이터 입력
    			line = readLine();
    			
    			// 공백 라인이 나올때까지 루프
    			while (line.length() > 0)	
    			{
    				// ScoreRecord 객체 생성 
    				ScoreRecord record = getScoreRecord(line);
    				
    				// 입력 오류 체크
    				if (record == null)
    				{
    					System.out.println("Error: Invalid data");
    					return;
    				}
    				
    				// ScoreRecord를 가지는  Team 객체 찾기
    				Team team = teams.get(record.getTeamNumber());
    				
    				// 객체가 없으면 Team 객체 생성
    				if (team == null)
    					team = new Team();
    				
    				// 팀의 기록 입력
    				team.appendRecord(record);
    				teams.put(team.getTeamNumber(), team);
    				
    				// 데이터 입력
    				line = readLine();
    			} // while (line.length() > 0)
    			
    			// 팀별로 결과 출력
    			for (Map.Entry<Integer, Team> entry : teams.entrySet())
    			{
    				int teamNumber = entry.getKey();
    				Team eTeam = entry.getValue();
    				
    				System.out.println(teamNumber + " " + eTeam.getProblems() + " " + eTeam.getTimes());
    			}
    	
    			count--;
    		} // while (count > 0)
    	}
    	
    	static String readLine() throws IOException
    	{
    		BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ));
    		
    		return reader.readLine();
    	}
    	
    	static ScoreRecord getScoreRecord(String line)
    	{
    		StringTokenizer tokens = new StringTokenizer(line, " ");
    		if (tokens.countTokens() != 4)
    		{
    			System.out.println("Error: invalid input data");
    			return null;
    		}
    		
    		return new ScoreRecord(line);
    	}
    }

ScoreRecord.java

    import java.util.*;
    
    public class ScoreRecord {
    	private int teamNumber;		// 팀번호
    	private int problem;		// 문제 
    	private int time;			// 걸린시간
    	private String format;		// 문제 상태
    	
    	ScoreRecord(String line)
    	{
    		StringTokenizer tokens = new StringTokenizer(line, " ");
    		
    		teamNumber = Integer.parseInt(tokens.nextToken());
    		problem = Integer.parseInt(tokens.nextToken());
    		time = Integer.parseInt(tokens.nextToken());
    		format = tokens.nextToken();
    	}
    	
    	int getTeamNumber()
    	{
    		return teamNumber;
    	}
    	
    	int getProblem()
    	{
    		return problem;
    	}
    	
    	int getTime()
    	{
    		return time;
    	}
    	
    	String getFormat()
    	{
    		return format;
    	}
    	
    	void show()
    	{
    		System.out.println("teamNumber: " + teamNumber + ", problem: " 
    				+ problem + ", time: " + time + ", format: " + format);
    	}
    	
    }

Team.java

    import java.util.*;
    
    public class Team {
    	private int teamNumber;								// 팀 번호
    	private TreeMap<Integer, Integer> scores; 			// Map<problem, time> 팀이 푼 문제와 해결하는데 걸린 시간
    	
    	Team()
    	{
    		teamNumber = 0;
    		scores = new TreeMap<Integer, Integer>();
    	}
    	
    	int getTeamNumber()
    	{
    		return teamNumber;
    	}
    	
    	void appendRecord(ScoreRecord record)
    	{
    		teamNumber = record.getTeamNumber();
    		String format = record.getFormat();
    
    		if (format.equals("I"))
    			append(record.getProblem(), 20);
    		
    		if (format.equals("C"))
    			append(record.getProblem(), record.getTime()); 
    	}
    	
    	int getProblems()
    	{
    		return scores.size();
    	}
    	
    	int getTimes()
    	{
    		int times = 0;
    		for (Map.Entry<Integer, Integer> entry : scores.entrySet())
    		{
    			times += entry.getValue();
    		}
    		
    		return times;
    	}
    	
    	void append(int problem, int time)
    	{
    		if (!scores.containsKey(problem))
    		{
    			Integer penalty = new Integer(0);
    			scores.put(problem, penalty);
    		}
    		
    		Integer times = scores.get(problem);
    		times += time;
    		scores.put(problem,times);
    	}
    	
    	void show()
    	{
    		System.out.println("No: " + teamNumber);
    		for (Map.Entry<Integer, Integer> entry : scores.entrySet())
    		{
    			System.out.println(entry.getKey() + " : " + entry.getValue());
    		}
    	}
    }

ParkPD

  • 입력 부분 만들기가 왜 이리 귀찮은지 ㅎㅎ

  • judge 은 안 해 봤습니다. -.-;;;

      /* @JUDGE_ID:parkpd 10038 C "test" */
      
      /* @BEGIN_OF_SOURCE_CODE */
      
      #include <iostream>
      #include <vector>
      #include <set>
      #include <strstream>
      #include <algorithm>
      
      using namespace std;
      
      #define _UNIT_TEST
      
      #ifdef _UNIT_TEST
      
      #include "../UnitTest++/src/UnitTest++.h"
      
      int main()
      {
      	UnitTest::RunAllTests();
      
      	char temp;
      	cin >> temp;
      
      	return 0;
      }
      
      #endif
      
      enum State
      {
      	NOT_TOUCHED = 0,
      	INCORRECT,
      	CORRECT
      };
      
      class CScore
      {
      public:
      	CScore() : m_Problem(0), m_Time(0), m_State(NOT_TOUCHED)
      	{
      	}
      
      	void InsertData(int time, bool result);
      
      	int m_Problem;
      	int m_Time;
      	State m_State;
      };
      
      void CScore::InsertData(int time, bool result)
      {
      	if (result)		// 풀기 성공.
      	{
      		m_Time += time;
      		m_State = CORRECT;
      	}
      	else	// 실패했다면
      	{
      		m_State = INCORRECT;
      		m_Time += 20;		// 20 초 패널티
      	}
      }
      
      class CTeamScore
      {
      public:
      	CTeamScore() : m_Id(-1), m_Corrects(0), m_Penalty(0)
      	{
      		for (int i = 0; i <= 9; ++i)
      		{
      			m_Scores[i].m_Problem = i;
      		}
      	}
      
      	void InsertData(int id, int problem, int time, bool result);
      	void CalcResult();
      
      	static bool IsMore(CTeamScore& a, CTeamScore& b);
      	static bool IsLess(CTeamScore& a, CTeamScore& b);
      	bool operator < (CTeamScore& other);
      
      	int m_Id;
      	int m_Corrects;
      	int m_Penalty;
      	CScore m_Scores[10];	
      };
      
      void CTeamScore::InsertData(int id, int problem, int time, bool result)
      {
      	m_Scores[problem].InsertData(time, result);
      	CalcResult();
      }
      
      void CTeamScore::CalcResult()
      {
      	m_Corrects = 0;
      	m_Penalty = 0;
      
      	for (int i = 1; i <= 9; ++i)
      	{
      		if (CORRECT == m_Scores[i].m_State)
      		{
      			++m_Corrects;
      			m_Penalty += m_Scores[i].m_Time;
      		}
      		else if (INCORRECT == m_Scores[i].m_State)
      		{
      			m_Penalty += m_Scores[i].m_Time;
      		}
      	}
      }
      
      bool CTeamScore::IsMore(CTeamScore& a, CTeamScore& b)
      {
      	return b < a;
      }
      
      bool CTeamScore::IsLess(CTeamScore& a, CTeamScore& b)
      {
      	return a < b;
      }
      
      bool CTeamScore::operator < (CTeamScore& other)
      {
      	// 점수 보고
      	if (m_Corrects != other.m_Corrects)
      	{
      		return m_Corrects < other.m_Corrects;
      	}
      	else
      	{
      		// 패널티 보고
      		if (other.m_Penalty != m_Penalty)
      		{
      			return other.m_Penalty < m_Penalty;
      		}
      
      		// 번호를 본다.
      		return (other.m_Id < m_Id);
      	}
      }
      
      class CScoreBoard
      {
      public:
      	CScoreBoard() : m_InsertedCount(0)
      	{
      		m_TeamScores.resize(101);
      		for (int i = 1; i <= 100; ++i)
      		{
      			m_TeamScores[i].m_Id = i;
      		}
      	}
      
      	void InsertData(int contestant, int problem, int time, char result);
      	void SortData();
      	void Print(ostream& output);
      
      	typedef vector<CTeamScore> Teams;
      	Teams m_TeamScores;
      	int m_InsertedCount;
      };
      
      void CScoreBoard::InsertData(int contestant, int problem, int time, char result)
      {
      	if (result != 'C' && result != 'I')
      	{
      		return;
      	}
      
      	m_TeamScores[contestant].InsertData(contestant, problem, time, (result == 'C'));
      	++m_InsertedCount;
      }
      
      void CScoreBoard::SortData()
      {
      	sort(m_TeamScores.begin(), m_TeamScores.end(), CTeamScore::IsMore);
      }
      
      void CScoreBoard::Print(ostream& output)
      {
      	Teams::iterator it = m_TeamScores.begin();
      	while (-1 != it->m_Id)
      	{
      		CTeamScore& score = *it;
      		output << score.m_Id << " " << score.m_Corrects << " "  << score.m_Penalty << "\n";
      		++it;
      	}
      }
      
      #ifndef _UNIT_TEST
      
      int main()
      {
      	return 0;
      }
      
      #else
      
      TEST_FIXTURE(CScore, InsertDataWithoutFailed)
      {
      	CHECK_EQUAL(NOT_TOUCHED, m_State);
      	InsertData(10, true);
      	CHECK_EQUAL(CORRECT, m_State);
      	CHECK_EQUAL(10, m_Time);
      }
      
      TEST_FIXTURE(CScore, InsertDataWithFailed)
      {
      	CHECK_EQUAL(NOT_TOUCHED, m_State);
      	InsertData(10, false);
      	CHECK_EQUAL(INCORRECT, m_State);
      	CHECK_EQUAL(20, m_Time);
      }
      
      TEST_FIXTURE(CScore, Example1)
      {
      	InsertData(10, false);
      	InsertData(21, true);
      	CHECK_EQUAL(41, m_Time);
      }
      
      TEST_FIXTURE(CScore, Example2)
      {
      	InsertData(11, true);
      	CHECK_EQUAL(CORRECT, m_State);
      	CHECK_EQUAL(11, m_Time);
      }
      
      TEST_FIXTURE(CTeamScore, Example1)
      {
      	InsertData(1, 2, 10, false);
      	CHECK_EQUAL(0, m_Corrects);
      	CHECK_EQUAL(20, m_Penalty);
      
      	InsertData(1, 2, 21, true);
      	CHECK_EQUAL(1, m_Corrects);
      	CHECK_EQUAL(41, m_Penalty);
      
      	InsertData(1, 1, 25, true);
      	CHECK_EQUAL(2, m_Corrects);
      	CHECK_EQUAL(66, m_Penalty);
      }
      
      TEST_FIXTURE(CTeamScore, Example2)
      {
      	InsertData(3, 1, 11, true);
      	CHECK_EQUAL(1, m_Corrects);
      	CHECK_EQUAL(11, m_Penalty);
      }
      
      TEST_FIXTURE(CScoreBoard, InsertData)
      {
      	InsertData(1, 2, 10, 'I');
      	InsertData(3, 1, 11, 'C');
      	InsertData(1, 2, 19, 'R');
      	InsertData(1, 2, 21, 'C');
      	InsertData(1, 1, 25, 'C');
      
      	CHECK_EQUAL(2, m_TeamScores[1].m_Corrects);
      	CHECK_EQUAL(66, m_TeamScores[1].m_Penalty);
      
      	CHECK_EQUAL(1, m_TeamScores[3].m_Corrects);
      	CHECK_EQUAL(11, m_TeamScores[3].m_Penalty);
      }
      
      struct FixtureCompare
      {
      	FixtureCompare()
      	{
      		a.m_Id = 1;
      		b.m_Id = 2;
      	}
      
      	CTeamScore a;
      	CTeamScore b;
      };
      
      TEST_FIXTURE(FixtureCompare, Compare)
      {
      	// 가장 우선순위는 문제 맞춘 횟수
      	b.m_Corrects = 1;
      	CHECK(a < b);
      	CHECK(!(b < a));
      
      	// a 도 같은 수를 맞췄다면, 패널티를 본다.
      	a.m_Corrects = 1;
      	a.m_Penalty = 1;
      	CHECK(a < b);
      	CHECK(!(b < a));
      
      	b.m_Penalty = 10;
      	CHECK(b < a);
      	CHECK(!(a < b));
      
      	// 둘 다 조건이 같을 때는 팀 번호 순서대로
      	a.m_Penalty = 10;
      	CHECK(b < a);
      	CHECK(!(a < b));
      }
      
      TEST_FIXTURE(CScoreBoard, SortData)
      {
      	InsertData(1, 2, 10, 'I');
      	InsertData(3, 1, 11, 'C');
      	InsertData(1, 2, 19, 'R');
      	InsertData(1, 2, 21, 'C');
      	InsertData(1, 1, 25, 'C');
      
      	SortData();
      
      	CHECK_EQUAL(2, m_TeamScores[0].m_Corrects);
      	CHECK_EQUAL(66, m_TeamScores[0].m_Penalty);
      
      	CHECK_EQUAL(1, m_TeamScores[1].m_Corrects);
      	CHECK_EQUAL(11, m_TeamScores[1].m_Penalty);
      
      	Print(cout);
      }
      
      #endif
      
      /* @END_OF_SOURCE_CODE */
    

kukuman

  • 소스가 나눠져 있습니다 .UVA submit 포기 ㅋ

  • Judge.java

      public class Judge{
      		private int contestant;
      		private int problem;
      		private int time;
      		private String status;
      		
      		public Judge(int contestant , int problem , int time , String status){
      			this.contestant = contestant;
      			this.problem = problem;
      			this.time = time;
      			this.status = status;
      		}
      
      		public int getContestant() {
      			return contestant;
      		}
      
      		public int getProblem() {
      			return problem;
      		}
      
      		public String getStatus() {
      			return status;
      		}
      
      		public int getTime() {
      			return time;
      		}
    
  • SolveResult.java

      import java.util.HashSet;
      import java.util.Set;
      
      
      public class SolveResult implements Comparable<SolveResult>{
      	private int contestant;
      	private int problemTotal = 0;
      	private int totalTime = 0;
      	private Set<Integer> solvedProblemSet = new HashSet<Integer>();
      	
      	public SolveResult(int contestant){
      		this.contestant = contestant;
      	}
      	
      	public void addJudge(Judge judge){
      		if(judge.getStatus().equals("C")){
      			solvedProblemSet.add(judge.getProblem());
      			problemTotal+= 1;
      			totalTime += judge.getTime();
      		}
      		if(judge.getStatus().equals("I")){
      			// 문제를 푼 이력이 있으면
      			if(solvedProblemSet.contains(judge.getProblem())){
      				//벌점 점수 20점 부과
      				totalTime += 20;
      			}
      		}
      	}
      	
      	public String toString(){
      		return contestant + " " + problemTotal + " " + totalTime;
      	}
      
      	public int getContestant() {
      		return contestant;
      	}
      
      	public int compareTo(SolveResult o) {
      		if(this.problemTotal>o.problemTotal)
      			return -1;
      		else if(this.problemTotal < o.problemTotal){
      			return 1;
      		} else if(this.totalTime > o.totalTime){
      			return -1;
      		} else if(this.totalTime < o.totalTime){
      			return 1;
      		}
      		
      		return 0;
      	}
      }
    
  • Solver.java

      import java.util.HashMap;
      import java.util.Map;
      import java.util.Set;
      import java.util.SortedSet;
      import java.util.Stack;
      import java.util.TreeSet;
      
      
      public class Solver {
      	private Stack<Judge> judges = new Stack<Judge>();
      	
      	public void inputJudge(int contestant , int problem , int time , String status) {
      		judges.push(new Judge(contestant,problem,time,status));
      	}
      	
      	public SolveResult[] doSolve(){
      		Map<Integer, SolveResult> resultMap = new HashMap<Integer, SolveResult>();
      		
      		while(!judges.isEmpty()){
      			Judge judge = judges.pop();
      			SolveResult solveResult = null;
      			if(resultMap.containsKey(judge.getContestant())){
      				solveResult = resultMap.get(judge.getContestant());
      			}else if(judge.getStatus().equals("C")){ //문제를 풀었을 때만 
      				solveResult = new SolveResult(judge.getContestant());
      			}
      			if(solveResult!=null){
      				solveResult.addJudge(judge);
      				resultMap.put(solveResult.getContestant(), solveResult);
      			}
      		}
      		
      		//맵의 데이터를 정렬 된 리스트에 삽입
      		Set<Integer> keys =resultMap.keySet();
      		SortedSet<SolveResult> sortedList = new TreeSet<SolveResult>();
      		for(Integer key : keys){
      			sortedList.add(resultMap.get(key));
      		}
      		SolveResult[] resultArray = new SolveResult[sortedList.size()];
      		return sortedList.toArray(resultArray);
      	}
      }
    
  • SolverTest.java

      import junit.framework.TestCase;
      
      
      public class SolverTest extends TestCase {
      	public void testSolverInput(){
      		Solver solver = new Solver();
      		solver.inputJudge(1,2,10,"I");
      		solver.inputJudge(3,1,11,"C");
      		solver.inputJudge(1,2,19,"R");
      		solver.inputJudge(1,2,21,"C");
      		solver.inputJudge(1,2,25,"C");
      		SolveResult [] results = solver.doSolve();
      		assertEquals(results.length,2);
      		for(SolveResult result : results){
      			System.out.println(result);
      		}
      	}
      }
    

Clone this wiki locally