[BOJ] 17822 원판 돌리기

Time Lapse :NONE

17822.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
133
134
135
136
137
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <memory.h>
using namespace std;

int N,M,T;
vector<int> circles[50];
int cmd[50][3];
bool visit[50][50];
int xi, di, ki;
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
bool flag;
long long ans = 0;


void rotate(int x, int d, int k){
for(int i=0;i<N;i++){
if((i+1)%x!=0)
continue;

if(d==0){
for(int j=0;j<k;j++){
int num = circles[i][M-1];
circles[i].erase(circles[i].end()-1);
circles[i].insert(circles[i].begin(),num);
}
}
else{
for(int j=0;j<k;j++){
int num = circles[i][0];
circles[i].erase(circles[i].begin());
circles[i].push_back(num);
}
}
}

}

void removeOrReplace(){
memset(visit,false,sizeof(visit));

for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(visit[i][j])
continue;
visit[i][j] = true;
if(circles[i][j]==0)
continue;
queue<pair<int,int>> q;
q.push(make_pair(i,j));
int num = circles[i][j];
while(!q.empty()){
int cur_x = q.front().second;
int cur_y = q.front().first;
q.pop();
for(int k=0;k<4;k++){
int near_x = cur_x+dx[k];
int near_y = cur_y+dy[k];
if(near_x==M)
near_x = 0;
if(near_x==-1)
near_x = M-1;
if(0<=near_x && near_x<M && 0<=near_y && near_y<N){

if(circles[near_y][near_x]==num && !visit[near_y][near_x]){
flag = false;
circles[i][j] = 0;
circles[near_y][near_x]=0;
visit[near_y][near_x]=true;
q.push(make_pair(near_y,near_x));
}
}
}
}
}
}
}

void caculate_avg(){
long double num = 0;
double cnt = 0;
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(circles[i][j]!=0){
cnt+=1;
num+=(double)circles[i][j];
}
}
}
if(cnt==0)
return ;

long double avg = num/cnt;
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(circles[i][j]!=0){
if((double)circles[i][j]>avg){
circles[i][j]-=1;
}
else if((double)circles[i][j]<avg){
circles[i][j]+=1;
}
}
}
}
}

int main(void){
cin>>N>>M>>T;
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
int num;
cin>>num;
circles[i].push_back(num);
}
}

//print_circle();
for(int i=0;i<T;i++){
cin>>xi>>di>>ki;
rotate(xi,di,ki);
flag = true;
removeOrReplace();
if(flag){
caculate_avg();
}
}
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
ans += circles[i][j];
}
}
cout<<ans<<endl;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/30/PS/BOJ/17822/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.