Last active
January 21, 2019 10:53
-
-
Save fpdjsns/f0c8f37f90f071262b041b5f7db7b3af to your computer and use it in GitHub Desktop.
[BOJ] 3665. 최종 순위 : https://www.acmicpc.net/problem/3665 위상정렬
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@fpdjsns
위 코드의 obj, tmp, tmpArr 변수명이나 swap 함수명의 의미가 모호합니다.
(n, m, a, b는 문제에 명시되어 있으므로 제외)
알고리즘 문제를 푸는 데에는 큰 상관은 없으나
의미 있는 변수명 사용을 통해 다른 누군가 코드를 봐도 알 수 있도록 하면 좋을 듯 합니다. :)