ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스타트와 링크
    백준알고리즘 2019. 9. 5. 01:49
    #include<iostream>
    #include<vector>
    
    using namespace std;
    
    int n;
    int s[100][100]; int ans = 987654321;
    
    void go(vector<int>& a, vector<int>& b, int sum, int suma, int idx) {
    	if (idx == n + 1) {
    		if (a.size() == b.size()) {
    			if (ans > abs(sum - suma))
    			{
    				ans = abs(sum - suma);
    				return;
    			}
    			else return;
    		}
    		else return;
    	}
    	int temp = 0;
    	for (int i = 0; i < a.size(); i++) {
    		temp += s[idx][a[i]];
    		temp += s[a[i]][idx];
    	}
    	sum += temp;
    	a.push_back(idx);
    	go(a, b, sum, suma, idx + 1);
    	sum -= temp;
    	a.pop_back();
    	temp = 0;
    	for (int i = 0; i < b.size(); i++) {
    		temp += s[idx][b[i]];
    		temp += s[b[i]][idx];
    	}
    	suma += temp;
    	b.push_back(idx);
    	go(a, b, sum, suma, idx + 1);
    	suma -= temp;
    	b.pop_back();
    	temp = 0;
    }
    
    int main() {
    	ios::sync_with_stdio(false);
    	cin.tie(NULL);
    	cout.tie(NULL);
    	cin >> n;
    	for (int i = 1; i <= n; i++) {
    		for (int j = 1; j <= n; j++) {
    			cin >> s[i][j];
    		}
    	}
    	vector<int> a;
    	vector<int> b;
    	go(a, b, 0, 0, 1);
    	cout << ans << '\n';
    	return 0;
    }

    SWEA A형 테스트 준비하면서 다시풀어보면 백트래킹 문제

    정말간단하지만 백트래킹의 정말정말 기초인듯 풀면서 편안해졌다.

    '백준알고리즘' 카테고리의 다른 글

    상근이의 여행  (0) 2019.09.08
    오큰수  (0) 2019.09.08
    단어 뒤집기  (0) 2019.09.05
    좋은수열  (0) 2019.09.05
    숨바꼭질2  (0) 2019.09.01

    댓글

Designed by Tistory.