335 words
2 minutes
[BOJ] 소풍
https://www.acmicpc.net/problem/2026
TimeLimit | MemoryLimit | Condition | TAG |
---|---|---|---|
2s | 128MB | (1 ≤ N ≤ 900 1 ≤ K ≤ 62 1 ≤ F ≤ 5,600) | BackTracking |
간단히 backtracking 구현하면 끝나는 문제입니다.
처음에 시작하는 index 번호에 대해서 교집합 처리로 하려고 했는데.. 그냥 구현으로는 시간초과를 피하기가 어려워서 그냥 직관적으로 보이는 풀이로 풀었습니다.
-1이 있는지도 모르고 계속 틀리다가.. 허헣 조심하십쇼
정답 코드
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
using namespace std;
using ll = long long;
int n, k, f;
bool connect[901][901];
int sizes[901];
bool visited[901];
bool connectVisited[901];
bool isPossible(int target){
for(int i = 1; i <= n; i++){
if(!visited[i]) continue;
if(!connect[target][i]) return false;
}
return true;
}
bool solution(int current, int depth){
if(depth == k) return true;
for(int i = 1; i <= n; i++){
if(!connect[current][i] || visited[i] || !isPossible(i)) continue;
visited[i] = true;
bool result = solution(i, depth+1);
if(result) return true;
visited[i] = false;
}
return false;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> k >> n >> f;
for(int i = 0; i < f; i++){
int a, b;
cin >> a >> b;
connect[a][b] = true;
connect[b][a] = true;
sizes[a]++;
sizes[b]++;
}
for(int i = 1; i <= n; i++){
if(sizes[i] + 1 < k) continue;
bool result = solution(i, 0);
// cout << result << "\n";
if(result){
int count = 0;
for(int i = 1; i <= n; i++){
if(visited[i]){
count ++;
cout << i << "\n";
}
if(count == k) return 0;
}
}
}
cout << -1;
return 0;
}
/*
1 6 8
1 2
1 3
1 6
2 3
2 6
3 6
4 5
5 6
*/