[BOJ] 17471 게리맨더링

Time Lapse :NONE

17471.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <memory.h>
#include <queue>

using namespace std;

#define MAXSIZE 11
int N, temp, picked=0, _index=0, popu=0;
int true_picked=0, false_picked=0;
int person[MAXSIZE];
int map[MAXSIZE][MAXSIZE];
bool choose[MAXSIZE];
vector<vector<int> > list;
int ans=987654321;

bool isPossible(vector<int> &list)
{
if(list.size()==0)
return false;
int cnt = 1;
queue<int> Q;
Q.push(list.at(0));
bool visited[MAXSIZE];
memset(visited,false,sizeof(visited));
for(int i=1;i<list.size();i++)
{
visited[list.at(i)]=true;
}
while(Q.empty()==0)
{
int x = Q.front();
Q.pop();

for(int i=1;i<=N;i++)
{
if(map[x][i]==1&&visited[i]==true)
{
cnt++;
visited[i]=false;
Q.push(i);
}
}
}
if(cnt==list.size())
return true;
return false;
}
void DFS(int idx)
{
if(idx>N)
{
vector<int> true_list, false_list;
for(int i=1;i<=N;i++)
{
if(choose[i])
true_list.push_back(i);
else
false_list.push_back(i);
}

if(isPossible(true_list)&&isPossible(false_list))
{
list.push_back(vector<int>());
for(int i=1;i<=N;i++)
if(choose[i])
list.at(_index).push_back(i);

_index++;
}
return ;
}

choose[idx]=true;
picked++;
DFS(idx+1);

choose[idx]=false;
picked--;
DFS(idx+1);

return ;
}

void calc()
{
if(list.size()==0)
cout<<"-1"<<endl;
else
{
for(const auto& i : list){
int total = 0;
for(const auto& j : i)
{
total += person[j];
}
ans = min(ans,abs(popu-2*total));
}
cout<<ans<<endl;
}
}

int main(void)
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);

cin>>N;
for(int i=1;i<=N;i++)
{
cin>>person[i];
popu+=person[i];
}

memset(map,0,sizeof(map));

for(int i=1;i<=N;i++)
{
int rep;
cin>>rep;
for(int j=0;j<rep;j++)
{
cin>>temp;
map[i][temp]=1;
}
}
DFS(1);
calc();
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/30/PS/BOJ/17471/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.