





class A_					:




   def __init__(self	:Optional[Any]    ,   _UpperCamelCase	:Optional[int]    ,   _UpperCamelCase	:Optional[Any]    ,   _UpperCamelCase	:List[Any] )->					Dict:
         __A          =				None
         __A          =				None
         __A          =				graph

         self._normalize_graph(_UpperCamelCase    ,   _UpperCamelCase )
         __A          =				len(_UpperCamelCase )
         __A          =				None




   def _lowerCAmelCase      (self	:Tuple    ,   _UpperCamelCase	:Optional[Any]    ,   _UpperCamelCase	:str )->					Tuple:
         if sources is int:
               __A          =				[sources]
         if sinks is int:
               __A          =				[sinks]

         if len(_UpperCamelCase ) == 0 or len(_UpperCamelCase ) == 0:
               return

         __A          =				sources[0]
         __A          =				sinks[0]

         # make fake vertex if there are more
         # than one source or sink
         if len(_UpperCamelCase ) > 1 or len(_UpperCamelCase ) > 1:
               __A          =				0
               for i in sources:
                     max_input_flow += sum(self.graph[i] )

               __A          =				len(self.graph ) + 1
               for room in self.graph:
                     room.insert(0    ,   0 )
               self.graph.insert(0    ,   [0] * size )
               for i in sources:
                     __A          =				max_input_flow
               __A          =				0

               __A          =				len(self.graph ) + 1
               for room in self.graph:
                     room.append(0 )
               self.graph.append([0] * size )
               for i in sinks:
                     __A          =				max_input_flow
               __A          =				size - 1




   def _lowerCAmelCase      (self	:Union[str, Any] )->					Optional[int]:
         if self.maximum_flow_algorithm is None:
               raise Exception('''You need to set maximum flow algorithm before.''' )
         if self.source_index is None or self.sink_index is None:
               return 0

         self.maximum_flow_algorithm.execute()
         return self.maximum_flow_algorithm.getMaximumFlow()






   def _lowerCAmelCase      (self	:List[Any]    ,   _UpperCamelCase	:Optional[Any] )->					Union[str, Any]:
         __A          =				algorithm(self )





class A_					:




   def __init__(self	:List[str]    ,   _UpperCamelCase	:Optional[Any] )->					int:
         __A          =				flow_network
         __A          =				flow_network.verticesCount
         __A          =				flow_network.sourceIndex
         __A          =				flow_network.sinkIndex
         # it's just a reference, so you shouldn't change
         # it in your algorithms, use deep copy before doing that
         __A          =				flow_network.graph
         __A          =				False




   def _lowerCAmelCase      (self	:Optional[int] )->					int:
         if not self.executed:
               self._algorithm()
               __A          =				True






   def _lowerCAmelCase      (self	:List[str] )->					Tuple:
         pass





class A_					(			_lowerCamelCase   ):




   def __init__(self	:Optional[int]    ,   _UpperCamelCase	:str )->					List[Any]:
         super().__init__(_UpperCamelCase )
         # use this to save your result
         __A          =				-1






   def _lowerCAmelCase      (self	:Optional[int] )->					str:
         if not self.executed:
               raise Exception('''You should execute algorithm before using its result!''' )

         return self.maximum_flow





class A_					(			_lowerCamelCase   ):




   def __init__(self	:Optional[int]    ,   _UpperCamelCase	:Optional[Any] )->					Tuple:
         super().__init__(_UpperCamelCase )

         __A          =				[[0] * self.verticies_count for i in range(self.verticies_count )]

         __A          =				[0] * self.verticies_count
         __A          =				[0] * self.verticies_count




   def _lowerCAmelCase      (self	:List[Any] )->					str:
         __A          =				self.verticies_count

         # push some substance to graph
         for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ):
               self.preflow[self.source_index][nextvertex_index] += bandwidth
               self.preflow[nextvertex_index][self.source_index] -= bandwidth
               self.excesses[nextvertex_index] += bandwidth

         # Relabel-to-front selection rule
         __A          =				[
             i
             for i in range(self.verticies_count )
             if i != self.source_index and i != self.sink_index
         ]

         # move through list
         __A          =				0
         while i < len(_UpperCamelCase ):
               __A          =				vertices_list[i]
               __A          =				self.heights[vertex_index]
               self.process_vertex(_UpperCamelCase )
               if self.heights[vertex_index] > previous_height:
                     # if it was relabeled, swap elements
                     # and start from 0 index
                     vertices_list.insert(0    ,   vertices_list.pop(_UpperCamelCase ) )
                     __A          =				0
               else:
                     i += 1

         __A          =				sum(self.preflow[self.source_index] )




   def _lowerCAmelCase      (self	:Tuple    ,   _UpperCamelCase	:str )->					Union[str, Any]:
         while self.excesses[vertex_index] > 0:
               for neighbour_index in range(self.verticies_count ):
                     # if it's neighbour and current vertex is higher
                     if (
                         self.graph[vertex_index][neighbour_index]
                         - self.preflow[vertex_index][neighbour_index]
                         > 0
                         and self.heights[vertex_index] > self.heights[neighbour_index]
                     ):
                           self.push(_UpperCamelCase    ,   _UpperCamelCase )

               self.relabel(_UpperCamelCase )




   def _lowerCAmelCase      (self	:Any    ,   _UpperCamelCase	:str    ,   _UpperCamelCase	:int )->					int:
         __A          =				min(
             self.excesses[from_index]    ,   self.graph[from_index][to_index] - self.preflow[from_index][to_index]    ,   )
         self.preflow[from_index][to_index] += preflow_delta
         self.preflow[to_index][from_index] -= preflow_delta
         self.excesses[from_index] -= preflow_delta
         self.excesses[to_index] += preflow_delta






   def _lowerCAmelCase      (self	:Any    ,   _UpperCamelCase	:Optional[int] )->					Optional[Any]:
         __A          =				None
         for to_index in range(self.verticies_count ):
               if (
                   self.graph[vertex_index][to_index]
                   - self.preflow[vertex_index][to_index]
                   > 0
               ) and (min_height is None or self.heights[to_index] < min_height):
                     __A          =				self.heights[to_index]

         if min_height is not None:
               __A          =				min_height + 1


if __name__ == "__main__":
       snake_case__					:							List[Any]													=     [0]
       snake_case__					:							int													=     [3]
       # graph = [
       #     [0, 0, 4, 6, 0, 0],
       #     [0, 0, 5, 2, 0, 0],
       #     [0, 0, 0, 0, 4, 4],
       #     [0, 0, 0, 0, 6, 6],
       #     [0, 0, 0, 0, 0, 0],
       #     [0, 0, 0, 0, 0, 0],
       # ]
       snake_case__					:							Optional[Any]													=     [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]]

       # prepare our network
       snake_case__					:							Tuple													=     FlowNetwork(graph, entrances, exits)
       # set algorithm
       flow_network.set_maximum_flow_algorithm(PushRelabelExecutor)
       # and calculate
       snake_case__					:							int													=     flow_network.find_maximum_flow()

       print(f'maximum flow is {maximum_flow}')












import numpy as np
from PIL import Image



def _a				(	lowerCamelCase:   np.ndarray					,				lowerCamelCase:   int					,				lowerCamelCase:   int )	->						np.ndarray:







      '''simple docstring'''






      __A          =				np.array(lowerCamelCase )
      if arr.shape[0] != arr.shape[1]:
            raise ValueError('''The input array is not a square matrix''' )
      __A          =				0
      __A          =				0
      __A          =				0
      __A          =				0

      # compute the shape of the output matrix
      __A          =				(arr.shape[0] - size) // stride + 1
      # initialize the output matrix with zeros of shape maxpool_shape
      __A          =				np.zeros((maxpool_shape, maxpool_shape) )

      while i < arr.shape[0]:
            if i + size > arr.shape[0]:
                  # if the end of the matrix is reached, break
                  break
            while j < arr.shape[1]:
                  # if the end of the matrix is reached, break
                  if j + size > arr.shape[1]:
                        break
                  # compute the maximum of the pooling matrix
                  __A          =				np.max(arr[i : i + size, j : j + size] )
                  # shift the pooling matrix by stride of column pixels
                  j += stride
                  mat_j += 1

            # shift the pooling matrix by stride of row pixels
            i += stride
            mat_i += 1

            # reset the column index to 0
            __A          =				0
            __A          =				0

      return updated_arr



def _a				(	lowerCamelCase:   np.ndarray					,				lowerCamelCase:   int					,				lowerCamelCase:   int )	->						np.ndarray:







      '''simple docstring'''






      __A          =				np.array(lowerCamelCase )
      if arr.shape[0] != arr.shape[1]:
            raise ValueError('''The input array is not a square matrix''' )
      __A          =				0
      __A          =				0
      __A          =				0
      __A          =				0

      # compute the shape of the output matrix
      __A          =				(arr.shape[0] - size) // stride + 1
      # initialize the output matrix with zeros of shape avgpool_shape
      __A          =				np.zeros((avgpool_shape, avgpool_shape) )

      while i < arr.shape[0]:
            # if the end of the matrix is reached, break
            if i + size > arr.shape[0]:
                  break
            while j < arr.shape[1]:
                  # if the end of the matrix is reached, break
                  if j + size > arr.shape[1]:
                        break
                  # compute the average of the pooling matrix
                  __A          =				int(np.average(arr[i : i + size, j : j + size] ) )
                  # shift the pooling matrix by stride of column pixels
                  j += stride
                  mat_j += 1

            # shift the pooling matrix by stride of row pixels
            i += stride
            mat_i += 1
            # reset the column index to 0
            __A          =				0
            __A          =				0

      return updated_arr


# Main Function
if __name__ == "__main__":
       from doctest import testmod

       testmod(name='avgpooling', verbose=True)

       # Loading the image
       snake_case__					:							Optional[Any]													=     Image.open('path_to_image')

       # Converting the image to numpy array and maxpooling, displaying the result
       # Ensure that the image is a square matrix

       Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()

       # Converting the image to numpy array and averagepooling, displaying the result
       # Ensure that the image is a square matrix

       Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()





