Skip to content

Instantly share code, notes, and snippets.

@fpdjsns
Last active January 21, 2019 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fpdjsns/f0c8f37f90f071262b041b5f7db7b3af to your computer and use it in GitHub Desktop.
Save fpdjsns/f0c8f37f90f071262b041b5f7db7b3af to your computer and use it in GitHub Desktop.
[BOJ] 3665. 최종 순위 : https://www.acmicpc.net/problem/3665 위상정렬
//
// Created by fpdjsns on 2019. 1. 21
// Copyright © 2019년 fpdjsns. All rights reserved.
//
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
vector<vector<bool>> adj;
vector<int> counts;
vector<int> topologicSort() {
int n = adj.size();
queue<int> q;
vector<int> ans;
vector<bool> check(n, false);
while (ans.size() < n) {
for (int i = 0; i < n; i++) {
if (counts[i] == 0 && !check[i]) {
q.push(i);
}
}
if (q.size() != 1) {
if (q.size() > 1) {
printf("?\n");
}
else if (ans.size() != n) {
printf("IMPOSSIBLE\n");
}
break;
}
int ansNum = q.front();
q.pop();
ans.push_back(ansNum);
check[ansNum] = true;
for (int i = 0; i < n; i++) {
if (adj[i][ansNum]) {
adj[i][ansNum] = false;
counts[i]--;
}
}
}
return ans;
}
void swap(int a, int b) {
if (adj[a][b]) {
adj[a][b] = false;
counts[a]--;
adj[b][a] = true;
counts[b]++;
}
else {
adj[a][b] = true;
counts[a]++;
adj[b][a] = false;
counts[b]--;
}
}
int main() {
int t;
cin >> t;
for (int cas = 0; cas<t; cas++) {
int n;
cin >> n;
adj = vector<vector<bool>>(n, vector<bool>(n, false));
counts = vector<int>(n, 0);
vector<int> scoreList;
int input;
for (int i = 0; i < n; i++) {
cin >> input;
input--;
for (int j = 0; j < scoreList.size(); j++) {
adj[input][scoreList[j]] = true;
counts[input]++;
}
scoreList.push_back(input);
}
int m, a, b;
cin >> m;
for (int i = 0; i < m; i++) {
cin >> a >> b;
a--; b--;
swap(a, b);
}
vector<int> ans = topologicSort();
if (ans.size() == n) {
for (int i = 0; i < n; i++)
printf("%d ", ans[i] + 1);
printf("\n");
}
}
return 0;
}
@vinus322
Copy link

. isImpossible은 사용하는 변수인가요?
. 입출력 라이브러리를 통일 하여 사용하는 것이 어떨까요? (cout/printf 혼용 x)
. 변수명을 보다 의미 있게 한다면 좋은 코드가 될 수 있을 것같습니다.

@fpdjsns
Copy link
Author

fpdjsns commented Jan 21, 2019

@vinus322

  • isImpossible은 삭제하겠습니다 ^^7
  • 로직 변경하다가 혼동이 되었군요 printf로 통일하겠습니다.
  • 혹시 어떤 변수명을 말씀하시는지 알려주실 수 있을까요???

@vinus322
Copy link

vinus322 commented Jan 21, 2019

@fpdjsns

  • 혹시 어떤 변수명을 말씀하시는지 알려주실 수 있을까요???
    위 코드의 obj, tmp, tmpArr 변수명이나 swap 함수명의 의미가 모호합니다.
    (n, m, a, b는 문제에 명시되어 있으므로 제외)
    알고리즘 문제를 푸는 데에는 큰 상관은 없으나
    의미 있는 변수명 사용을 통해 다른 누군가 코드를 봐도 알 수 있도록 하면 좋을 듯 합니다. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment