src
stringlengths 95
64.6k
| complexity
stringclasses 7
values | problem
stringlengths 6
50
| from
stringclasses 1
value |
---|---|---|---|
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args) throws IOException {
InputStream input = System.in;
OutputStream output = System.out;
InputReader in = new InputReader(new FileReader(new File("input.txt")));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
Solution s = new Solution();
s.solve(1, in, out);
out.close();
}
static class Solution {
static int[][] grid;
static int[] dx = {0, 0, 1, -1};
static int[] dy = {1, -1, 0, 0};
static int n, m;
public void solve(int cs, InputReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
int k = in.nextInt();
grid = new int[n][m];
for (int[] d : grid)
Arrays.fill(d, -1);
for (int i = 0; i < k; i++) {
Pair tree = new Pair(in.nextInt()-1, in.nextInt()-1);
bfs(tree);
}
int max = 0, idx1 = 0, idx2 = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] > max) {
max = grid[i][j];
idx1 = i;
idx2 = j;
}
}
}
out.printf("%d %d%n", idx1+1, idx2+1);
}
public boolean isValid(int i, int j) {
return i >= 0 && i < n && j >= 0 && j < m;
}
static class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public void bfs(Pair src) {
Queue<Pair> q = new LinkedList<>();
grid[src.x][src.y] = 0;
q.add(src);
while (!q.isEmpty()) {
Pair p = q.poll();
for (int k = 0; k < 4; k++) {
int nx = p.x+dx[k];
int ny = p.y+dy[k];
if (isValid(nx, ny)) {
if (grid[nx][ny] > grid[p.x][p.y]+1 || grid[nx][ny] == -1) {
grid[nx][ny] = grid[p.x][p.y] + 1;
q.add(new Pair(nx, ny));
}
}
}
}
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream i) {
br = new BufferedReader(new InputStreamReader(i), 32768);
st = null;
}
public InputReader(FileReader s) {
br = new BufferedReader(s);
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* @author igor_kz
*/
public class C35 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter("output.txt");
int n = in.nextInt() , m = in.nextInt();
int k = in.nextInt();
int[] x = new int[k];
int[] y = new int[k];
int res = 0;
for (int i = 0 ; i < k ; i++) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int xx = 1 , yy = 1;
for (int i = 1 ; i <= n ; i++)
for (int j = 1 ; j <= m ; j++) {
int cnt = Integer.MAX_VALUE;
for (int l = 0 ; l < k ; l++) {
int time = Math.abs(i - x[l]) + Math.abs(j - y[l]);
cnt = Math.min(cnt , time);
}
if (cnt > res) {
res = cnt;
xx = i;
yy = j;
}
res = Math.max(res , cnt);
}
out.print(xx + " " + yy);
out.close();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class Main{
public static void main(String[] Args) throws Exception {
Scanner sc = new Scanner(new FileReader("input.txt"));
int n,m,k;
Integer lx,ly;
boolean d[][];
n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt();
d = new boolean [n+1][m+1];
for(int i=0;i<=n;++i)
for(int j=0;j<=m;++j)
d[i][j]=false;
Queue< pair > q = new LinkedList< pair >();
lx = ly = -1;
for(int i=0;i<k;++i){
int x,y; x = sc.nextInt(); y = sc.nextInt();
q.add(new pair(x,y)); lx = x; ly = y;
d[x][y]=true;
}
int dx [] = {0,0,1,-1};
int dy [] = {-1,1,0,0};
while(!q.isEmpty()){
pair tp = q.remove();
int x = tp.x; int y = tp.y;
for(int i=0;i<4;++i){
int nx = x+dx[i]; int ny = y+dy[i];
if(nx<1 || nx>n || ny<1 || ny>m || d[nx][ny] ) continue;
d[nx][ny]=true;
q.add(new pair(nx,ny));
lx = nx; ly = ny;
}
}
FileWriter fw = new FileWriter("output.txt");
fw.write(lx.toString()); fw.write(" "); fw.write(ly.toString());;
fw.flush();
}
}
class pair {
public int x,y;
public pair(int _x,int _y){ x = _x; y = _y; }
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class C
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
void openInput(String file)
{
if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
else
{
try{
fstream = new FileInputStream(file);
in = new DataInputStream(fstream);
is = new BufferedReader(new InputStreamReader(in));
}catch(Exception e)
{
System.err.println(e);
}
}
}
void readNextLine()
{
try {
line = is.readLine();
inputParser = new StringTokenizer(line, " ");
//System.err.println("Input: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
int NextInt()
{
String n = inputParser.nextToken();
int val = Integer.parseInt(n);
//System.out.println("I read this number: " + val);
return val;
}
String NextString()
{
String n = inputParser.nextToken();
return n;
}
void closeInput()
{
try {
is.close();
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
public static void main(String [] argv)
{
String filePath=null;
if(argv.length>0)filePath=argv[0];
C c = new C(filePath);
}
public C(String inputFile)
{
inputFile="input.txt";
openInput(inputFile);
PrintWriter writer=null;
try {
writer = new PrintWriter("output.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
readNextLine();
int N=NextInt();
int M=NextInt();
readNextLine();
int K=NextInt();
readNextLine();
int [] [] p = new int[N][M];
int [] [] init = new int [K][2];
for(int i=0; i<K; i++)
{
int x=NextInt()-1;
int y=NextInt()-1;
p[x][y]=0;
init[i][0]=x;
init[i][1]=y;
}
int max=-1;
int maxX=-1, maxY=-1;
for(int i=0; i<N; i++)
for(int j=0; j<M; j++)
{
p[i][j]=10000;
for(int k=0; k<K; k++)
{
int n=Math.abs(init[k][0]-i)+Math.abs(init[k][1]-j);
if(n<p[i][j])p[i][j]=n;
}
if(p[i][j]>max)
{
max=p[i][j];
maxX=i+1;
maxY=j+1;
}
}
writer.println( maxX+" "+maxY);
closeInput();
writer.close();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class FireAgain {
static int dx[] = { 0, 0, 1, -1 };
static int dy[] = { 1, -1, 0, 0 };
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("input.txt"));
BufferedWriter write = new BufferedWriter(new FileWriter("output.txt"));
int n = sc.nextInt();
int m = sc.nextInt();
boolean[][] v = new boolean[n][m];
int k = sc.nextInt();
Queue<Integer> q = new LinkedList<Integer>();
for (int i = 0; i < k; i++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
q.add(x);
q.add(y);
v[x][y] = true;
}
int lastx = 0;
int lasty = 0;
while (!q.isEmpty()) {
lastx = q.poll();
lasty = q.poll();
for (int i = 0; i < 4; i++) {
int r = lastx + dx[i];
int c = lasty + dy[i];
if (r >= 0 && c >= 0 && r < n && c < m && !v[r][c]) {
v[r][c] = true;
q.add(r);
q.add(c);
}
}
}
write.write((lastx + 1) + " " + (lasty + 1));
write.close();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.Point;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String dimensions = br.readLine();
String extractDim = "";
int n = 0, m;
for (int i = 0 ; i < dimensions.length() ; i++)
{
if(dimensions.charAt(i) == ' ')
{
n = Integer.parseInt(extractDim);
extractDim = "";
continue;
}
extractDim += dimensions.charAt(i);
}
m = Integer.parseInt(extractDim);
String burningTrees = br.readLine();
int k = Integer.parseInt(burningTrees);
Point[] coord = new Point[k];
String coordSet = br.readLine();
int spaceCount = 0;
String newCoord = "";
int s = 0;
for(int i = 0 ; i < coordSet.length() ; i++)
{
if(coordSet.charAt(i) == ' ')
spaceCount++;
if(spaceCount == 2)
{
String extractCoord = "";
int x = 0, y;
for (int j = 0 ; j < newCoord.length() ; j++)
{
if(newCoord.charAt(j) == ' ')
{
x = Integer.parseInt(extractCoord);
extractCoord = "";
continue;
}
extractCoord += newCoord.charAt(j);
}
y = Integer.parseInt(extractCoord);
coord[s] = new Point(x,y);
s++;
newCoord = "";
spaceCount = 0;
continue;
}
newCoord += coordSet.charAt(i);
}
String extractCoord = "";
int x = 0, y;
for (int j = 0 ; j < newCoord.length() ; j++)
{
if(newCoord.charAt(j) == ' ')
{
x = Integer.parseInt(extractCoord);
extractCoord = "";
continue;
}
extractCoord += newCoord.charAt(j);
}
y = Integer.parseInt(extractCoord);
coord[s] = new Point(x,y);
s++;
br.close();
int[][] forest = new int[n+2][m+2];
for(int i = 0 ; i < forest.length ; i++)
{
for(int j = 0 ; j < forest[i].length ; j++)
{
if(i == 0 || i == n+1 || j == 0 || j == m+1 )
forest[i][j] = 0;
else
forest[i][j] = 1;
}
}
Queue<Point> q = new LinkedList<>();
for(int i = 0 ; i < coord.length ; i++)
{
forest[coord[i].x][coord[i].y] = 0;
q.add(coord[i]);
}
Point tree = new Point();
while(!q.isEmpty())
{
Point temp = q.remove();
forest[temp.x][temp.y] = 0;
if(q.isEmpty())
tree = new Point(temp.x ,temp.y);
for(int i = -1 ; i <= 1 ; i++)
{
for(int j = -1; j <= 1; j++)
{
if(i != 0 && j != 0 || i == 0 && j == 0)
continue;
if(forest[temp.x+i][temp.y+j] == 0)
continue;
else
{
forest[temp.x+i][temp.y+j] = 0;
q.add(new Point(temp.x+i , temp.y+j));
}
}
}
}
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
bw.write(tree.x + " " + tree.y);
bw.close();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
//import java.util.Scanner;
public class Codes {
public static void main(String[] args) throws IOException {
InputReader input = new InputReader(new FileReader(("input.txt")));
int n = input.nextInt();
int m = input.nextInt();
int k = input.nextInt();
boolean[][] visited = new boolean[n][m];
Queue<Point> bfs = new LinkedList<Point>();
for (int i = 0; i < k; i++) {
int x = input.nextInt();
int y = input.nextInt();
visited[x - 1][y - 1] = true;
bfs.add(new Point(x - 1, y - 1));
}
Point last = bfs.peek();
while(!bfs.isEmpty()) {
Point current = bfs.poll();
int curX = current.x;
int curY = current.y;
//the upper tree
if(curX - 1 >= 0) {
if(!visited[curX - 1][curY]) {
bfs.add(new Point(curX - 1,curY));
visited[curX - 1][curY] = true;
}
}
//the tree to the right
if(curY + 1 < m) {
if(!visited[curX][curY + 1]) {
bfs.add(new Point(curX ,curY + 1));
visited[curX][curY + 1] = true;
}
}
//the lower tree
if(curX + 1 < n) {
if(!visited[curX + 1][curY]) {
bfs.add(new Point(curX + 1,curY));
visited[curX + 1][curY] = true;
}
}
//the point to the left
if(curY - 1 >= 0) {
if(!visited[curX][curY - 1]) {
bfs.add(new Point(curX ,curY - 1));
visited[curX][curY - 1] = true;
}
}
if(bfs.peek()!= null)
last = bfs.peek();
}
PrintWriter out = new PrintWriter(new File("output.txt"));
out.println((last.x + 1) + " " + (last.y + 1));
out.close();
//System.out.println((last.x + 1) + " " + (last.y + 1));
}
static class Point {
int x;
int y;
public Point(int x2, int y2) {
x = x2;
y = y2;
}
}
/**
* This reader class is NOT Mine.
**/
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader(FileReader stream) {
reader = new BufferedReader(stream);
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.*;
import java.io.*;
import java.util.*;
public class Abc {
public static void main(String[] args) throws IOException {
// FastReader sc = new FastReader();
Scanner sc=new Scanner(new FileReader("input.txt"));
PrintWriter out=new PrintWriter(new File("output.txt"));
int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt();
boolean vis[][]=new boolean[n][m];
LinkedList<Integer> q=new LinkedList<>();
for (int i=0;i<k;i++){
int x=sc.nextInt()-1,y=sc.nextInt()-1;
vis[x][y]=true;
q.add(x);q.add(y);
}
int lastx=-1,lasty=-1;
int dirX[]={1,-1,0,0},dirY[]={0,0,1,-1};
while (!q.isEmpty()){
int x=q.removeFirst();
int y=q.removeFirst();
lastx=x;lasty=y;
for (int i=0;i<4;i++){
int newx=x+dirX[i],newy=y+dirY[i];
if (newx>=0 && newx<n && newy>=0 && newy<m && !vis[newx][newy]){
vis[newx][newy]=true;
q.add(newx);q.add(newy);
}
}
}
out.println((lastx+1)+" "+(lasty+1));
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static class Point {
int x;
int y;
Point(int a, int b) {
x = a;
y = b;
}
@Override
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
}
public static void main(String[] args) throws IOException {
File f = new File("input.txt");
Scanner sc = new Scanner(f);
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")));
int n = sc.nextInt();
int m = sc.nextInt();
boolean[][] board = new boolean[n][m];
int count = sc.nextInt();
Point[] burningTrees = new Point[count];
for (int i=0; i<count; i++) {
burningTrees[i] = new Point(sc.nextInt() - 1,sc.nextInt() - 1);
}
Point last = findLastPoint(board,burningTrees);
bw.append((last.x + 1) + " " + (last.y + 1) + "\n");
bw.flush();
bw.close();
sc.close();
}
public static Point findLastPoint(boolean[][] board, Point[] burningTree){
Queue<Point> queue = new LinkedList<Point>();
for(int i = 0; i <burningTree.length; i++ ) {
queue.add(burningTree[i]);
board[burningTree[i].x][burningTree[i].y] = true;
}
Point lastPoint = new Point(-1,-1);
while (!queue.isEmpty()) {
Point p = queue.poll();
lastPoint = p;
ArrayList<Point> neighbours = getNeighbours(p,board);
for(int i = 0; i <neighbours.size(); i++ ) {
queue.add(neighbours.get(i));
board[neighbours.get(i).x][neighbours.get(i).y] = true;
}
}
return lastPoint;
}
public static ArrayList<Point> getNeighbours(Point p, boolean[][] board){
ArrayList<Point> neighbours = new ArrayList<>();
for(int i = -1; i <=1; i++ ){
for(int j = -1; j <= 1; j++ ){
if(Math.abs(i) != Math.abs(j)) {
int x = p.x + i;
int y = p.y + j;
if (x >= 0 && x < board.length && y >= 0 && y < board[0].length) {
if (board[x][y] == false) {
neighbours.add(new Point(x,y));
}
}
}
}
}
return neighbours;
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
import java.math.*;
public class C implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
Random rnd;
short[] qx, qy;
boolean[][] used;
final int[] dx = {1, -1, 0, 0};
final int[] dy = {0, 0, 1, -1};
void solve() throws IOException {
int n = nextInt(), m = nextInt();
qx = new short[n * m];
qy = new short[n * m];
used = new boolean[n][m];
int k = nextInt(), qs = 0, qt = 0;
for(int i = 0; i < k; i++) {
int x = nextInt() - 1, y = nextInt() - 1;
used[x][y] = true;
qx[qt] = (short) x;
qy[qt] = (short) y;
++qt;
}
int rx = 0, ry = 0;
while(qs < qt) {
int cx = qx[qs], cy = qy[qs];
++qs;
rx = cx;
ry = cy;
for(int z = 0; z < 4; z++) {
int nx = cx + dx[z], ny = cy + dy[z];
if(nx >= 0 && ny >= 0 && nx < n && ny < m && !used[nx][ny]) {
used[nx][ny] = true;
qx[qt] = (short) nx;
qy[qt] = (short) ny;
++qt;
}
}
}
out.println((rx + 1) + " " + (ry + 1));
}
public static void main(String[] args) {
final boolean oldChecker = false;
if(oldChecker) {
new Thread(null, new C(), "yarrr", 1 << 24).start();
} else {
new C().run();
}
}
public void run() {
try {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
} catch (FileNotFoundException e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
rnd = new Random();
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(42);
}
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.util.*;
import java.io.*;
import java.math.*;
public class Main1
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
public double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
}
///////////////////////////////////////////////////////////////////////////////////////////
// RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL //
// RR RRR AAAAA HHH HHH IIIIIIIIIII LLL //
// RR RRR AAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHHHHHHHHHH III LLL //
// RRRRRR AAA AAA HHHHHHHHHHH III LLL //
// RR RRR AAAAAAAAAAAAA HHH HHH III LLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL //
// RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL //
///////////////////////////////////////////////////////////////////////////////////////////
static class pair
{
int x;
int y;
public pair (int k, int p)
{
x = k;
y = p;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
pair pair = (pair) o;
return x == pair.x && y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
public static void main(String[] args)throws IOException
{
/*PrintWriter out= new PrintWriter(new File("input.txt"));
Reader sc=new Reader();*/
Scanner sc = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter("output.txt");
Queue<pair> q=new LinkedList<>();
int n=sc.nextInt();
int m=sc.nextInt();
int t=sc.nextInt();
int mark[][]=new int[n+2][m+2];
while(t-->0)
{
int a=sc.nextInt();int b=sc.nextInt();
mark[a][b]=1;
q.add(new pair(a,b));
}
int ansx=1;int ansy=1;
while(q.size()!=0)
{
pair p=q.remove();
if(mark[Math.max(1,p.x-1)][p.y]==0)
{
q.add(new pair(Math.max(1,p.x-1),p.y));
mark[Math.max(1,p.x-1)][p.y]=1;
ansx=Math.max(1,p.x-1);
ansy=p.y;
}
if(mark[Math.min(n,p.x+1)][p.y]==0)
{
q.add(new pair(Math.min(n,p.x+1),p.y));
mark[Math.min(n,p.x+1)][p.y]=1;
ansx=Math.min(n,p.x+1);
ansy=p.y;
}
if(mark[p.x][Math.max(1,p.y-1)]==0)
{
q.add(new pair(p.x,Math.max(1,p.y-1)));
mark[p.x][Math.max(1,p.y-1)]=1;
ansx=p.x;
ansy=Math.max(1,p.y-1);
}
if(mark[p.x][Math.min(m,p.y+1)]==0)
{
q.add(new pair(p.x,Math.min(m,p.y+1)));
mark[p.x][Math.min(m,p.y+1)]=1;
ansx=p.x;
ansy=Math.min(m,p.y+1);
}
}
out.println(ansx+" "+ansy);
out.flush();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class MainF {
public static void main(String[]args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(new File("input.txt")));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")));
String S = br.readLine();
String[]J = S.split(" ");
int N = Integer.parseInt(J[0]);
int M = Integer.parseInt(J[1]);
int K = Integer.parseInt(br.readLine());
int[]x = new int[K];
int[]y = new int[K];
S = br.readLine();
J = S.split(" ");
for(int i = 0; i<2*K; i = i + 2){
x[i/2] = Integer.parseInt(J[i]);
y[i/2] = Integer.parseInt(J[i+1]);
}
int ans = -1;
int ansX = -1;
int ansY = -1;
for (int i = 1; i<=N; i++){
for (int j = 1; j<=M; j++){
int W = M + N;
for (int k = 0; k<K; k++){
W = Math.min(W, Math.abs(i-x[k]) + Math.abs(j-y[k]));
}
if (W < ans)continue;
ans = W;
ansX = i;
ansY = j;
}
}
bw.write(Integer.toString(ansX)+" "+Integer.toString(ansY));
br.close();
bw.close();
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.Collection;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Queue;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Nafiur Rahman Khadem Shafin 🙂
*/
public class Main {
public static void main (String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader (inputStream);
PrintWriter out = new PrintWriter (outputStream);
ProblemCFireAgain solver = new ProblemCFireAgain ();
solver.solve (1, in, out);
out.close ();
}
static class ProblemCFireAgain {
private static final byte[] dx = {-1, 0, 0, 1};
private static final byte[] dy = {0, -1, 1, 0};
private static int[][] lvl;
private static int max;
private static int n;
private static int m;
private static int k;
private static ProblemCFireAgain.Pair[] bgn;
private static ProblemCFireAgain.Pair res;
private static void bfs2d () {
Queue<ProblemCFireAgain.Pair> bfsq = new LinkedList<ProblemCFireAgain.Pair> ();
for (ProblemCFireAgain.Pair src : bgn) {
lvl[src.a][src.b] = 0;
bfsq.add (src);
}
while (!bfsq.isEmpty ()) {
ProblemCFireAgain.Pair op = bfsq.poll ();
int plvl = lvl[op.a][op.b];
// System.out.println ("ber hoise "+op+" "+plvl);
if (plvl>max) {
res = op;
max = plvl;
}
for (int i = 0; i<4; i++) {
int newX = op.a+dx[i];
int newY = op.b+dy[i];
// System.out.println (newX+" "+newY+" "+n+" "+m);
if (newX>0 && newX<=n && newY>0 && newY<=m && lvl[newX][newY] == -1) {
bfsq.add (new ProblemCFireAgain.Pair (newX, newY));
lvl[newX][newY] = (plvl+1);
// System.out.println ("dhukse "+newX+" "+newY);
}
}
}
}
public void solve (int testNumber, InputReader _in, PrintWriter _out) {
/*
* file input-output 😮. Multi source bfs. Same as snackdown problem.
* */
try (InputReader in = new InputReader (new FileInputStream ("input.txt"));
PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter ("output.txt")))) {
n = in.nextInt ();
m = in.nextInt ();
k = in.nextInt ();
bgn = new ProblemCFireAgain.Pair[k];
for (int i = 0; i<k; i++) {
bgn[i] = new ProblemCFireAgain.Pair (in.nextInt (), in.nextInt ());
}
max = Integer.MIN_VALUE;
lvl = new int[n+5][m+5];
for (int i = 0; i<n+4; i++) {
Arrays.fill (lvl[i], -1);
}
bfs2d ();
// System.out.println (max);
out.println (res);
} catch (Exception e) {
// e.printStackTrace ();
}
}
private static class Pair {
int a;
int b;
Pair (int a, int b) {
this.a = a;
this.b = b;
}
public String toString () {
return a+" "+b;
}
public boolean equals (Object o) {
if (this == o) return true;
if (!(o instanceof ProblemCFireAgain.Pair)) return false;
ProblemCFireAgain.Pair pair = (ProblemCFireAgain.Pair) o;
return a == pair.a && b == pair.b;
}
public int hashCode () {
return Objects.hash (a, b);
}
}
}
static class InputReader implements AutoCloseable {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader (InputStream stream) {
reader = new BufferedReader (new InputStreamReader (stream));
tokenizer = null;
}
public String next () {
while (tokenizer == null || !tokenizer.hasMoreTokens ()) {
try {
String str;
if ((str = reader.readLine ()) != null) tokenizer = new StringTokenizer (str);
else return null;//to detect eof
} catch (IOException e) {
throw new RuntimeException (e);
}
}
return tokenizer.nextToken ();
}
public int nextInt () {
return Integer.parseInt (next ());
}
public void close () throws Exception {
reader.close ();
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class C35C_BFS_Fire {
public static boolean[][] burning;
public static LinkedList<int[]> LitTrees; //which is best to use
public static int N, M;
public static int[] lastTree;
public static void main(String[] args) throws IOException {
// InputStreamReader stream = new InputStreamReader(System.in);
// BufferedReader input = new BufferedReader(stream);
BufferedReader input = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
StringTokenizer dataR = new StringTokenizer(input.readLine());
N = Integer.parseInt(dataR.nextToken());
M = Integer.parseInt(dataR.nextToken());
burning = new boolean[N+1][M+1];
StringTokenizer dataR1 = new StringTokenizer(input.readLine());
int K = Integer.parseInt(dataR1.nextToken());
StringTokenizer dataR2 = new StringTokenizer(input.readLine());
LitTrees = new LinkedList<int[]>();
for (int j = 0; j < K; j++){
int x = Integer.parseInt(dataR2.nextToken());
int y = Integer.parseInt(dataR2.nextToken());
int[] coord = {x, y};
LitTrees.add(coord);
burning[x][y] = true;
}
// while(ExistsAliveTree()){
// spread();
// }
spread();
// System.out.println(LitTrees.getLast()[0] + " " + LitTrees.getLast()[1]);
out.println(lastTree[0] + " " + lastTree[1]);
out.close();
}
public static void spread(){
while(!LitTrees.isEmpty()){
int[] studying = LitTrees.removeFirst(); //is iterator faster
int[] studying1 = {studying[0]-1, studying[1]};
int[] studying2 = {studying[0], studying[1]-1};
int[] studying3 = {studying[0], studying[1]+1};
int[] studying4 = {studying[0]+1, studying[1]};
if (studying1[0] >= 1 && !burning[studying1[0]][studying1[1]]){
LitTrees.add(studying1);
burning[studying1[0]][studying1[1]] = true;
}
if (studying2[1] >= 1 && !burning[studying2[0]][studying2[1]]){
LitTrees.add(studying2);
burning[studying2[0]][studying2[1]] = true;
}
if (studying3[1] < M+1 && !burning[studying3[0]][studying3[1]]){
LitTrees.add(studying3);
burning[studying3[0]][studying3[1]] = true;
}
if (studying4[0] < N+1 && !burning[studying4[0]][studying4[1]]){
LitTrees.add(studying4);
burning[studying4[0]][studying4[1]] = true;
}
lastTree = studying;
}
}
public static boolean ExistsAliveTree() {
if (LitTrees.size() == N*M){
return false;
} else{
return true;
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
//package round35;
import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class C {
Scanner in;
PrintWriter out;
// String INPUT = "3 3 1 1 1";
String INPUT = "";
void solve()
{
int n = ni();
int m = ni();
int k = ni();
int[] x = new int[k];
int[] y = new int[k];
for(int i = 0;i < k;i++){
x[i] = ni() - 1;
y[i] = ni() - 1;
}
int max = -1;
int maxi = -1;
int maxj = -1;
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
int min = Integer.MAX_VALUE;
for(int l = 0;l < k;l++){
min = Math.min(min, Math.abs(x[l] - i) + Math.abs(y[l] - j));
}
if(min > max){
max = min;
maxi = i;
maxj = j;
}
}
}
out.println((maxi+1) + " " + (maxj+1));
}
void run() throws Exception
{
in = INPUT.isEmpty() ? new Scanner(new File("input.txt")) : new Scanner(INPUT);
out = INPUT.isEmpty() ? new PrintWriter("output.txt") : new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception
{
new C().run();
}
int ni() { return Integer.parseInt(in.next()); }
void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); }
static String join(int[] a, int d){StringBuilder sb = new StringBuilder();for(int v : a){sb.append(v + d + " ");}return sb.toString();}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class c {
static boolean used[][];
static int n;
static int m;
static int a[][];
public static void main(String args[])throws Exception{
Scanner in =new Scanner(new File("input.txt"));//System.in);//
PrintWriter out=new PrintWriter(new File("output.txt"));//System.out);//
n = in.nextInt();
m = in.nextInt();
int k = in.nextInt();
//a=new int[n+1][m+1];
/*for (int i = 1; i<=n; i++)
for (int j = 1; j<=m; j++)
a[i][j] = 40001;
*/
int x[]=new int[k];
int y[]=new int[k];
for (int i = 0; i<k; i++){
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int max = 0;
int xx = 1; int yy= 1;
for (int i = 1; i<=n; i++)
for (int j = 1; j<=m; j++){
int count = Integer.MAX_VALUE;
for (int l =0; l<k; l++)
count = Math.min(Math.abs(i - x[l]) + Math.abs(j - y[l]), count);
if (max < count){
max = count;
xx = i; yy = j;
}
}
out.println(xx + " " + yy);
out.close();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.ArrayDeque;
import java.util.Arrays;
public class Main {
private static StreamTokenizer in;
private static PrintWriter out;
private static BufferedReader inB;
private static int nextInt() throws Exception{
in.nextToken();
return (int)in.nval;
}
private static String nextString() throws Exception{
in.nextToken();
return in.sval;
}
static{
/*
inB = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
/**/
//*
try {
inB = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
out = new PrintWriter(new FileOutputStream("output.txt"));
} catch(Exception e) {}
/**/
in = new StreamTokenizer(inB);
}
private static int[][] mind;
private static boolean[][] used;
private static int n,m;
public static void main(String[] args)throws Exception {
n = nextInt();
m = nextInt();
int k = nextInt();
int[][] mas = new int[k][2];
for(int i = 0; i<k; i++) {
mas[i][0] = nextInt()-1;
mas[i][1] = nextInt()-1;
}
mind = new int[n][m];
used = new boolean[n][m];
for(int i = 0; i<n; i++) {
Arrays.fill(mind[i], Integer.MAX_VALUE);
}
ArrayDeque<int[]> ad = new ArrayDeque<int[]>();
for(int i = 0; i<k; i++) {
ad.add(new int[] {mas[i][0], mas[i][1], 0});
}
while(!ad.isEmpty()) {
int[] cur = ad.remove();
if(used[cur[0]][cur[1]])continue;
int x = cur[0]; int y = cur[1]; int d = cur[2];
mind[x][y] = ++d;
used[x][y] = true;
//if(isValid(x+1,y+1) && !used[x+1][y+1]) ad.add(new int[] {x+1, y+1, d});
if(isValid(x+1,y) && !used[x+1][y]) ad.add(new int[] {x+1, y, d});
//if(isValid(x+1,y-1) && !used[x+1][y-1]) ad.add(new int[] {x+1, y-1, d});
if(isValid(x,y+1) && !used[x][y+1]) ad.add(new int[] {x, y+1, d});
if(isValid(x,y-1) && !used[x][y-1]) ad.add(new int[] {x, y-1, d});
//if(isValid(x-1,y+1) && !used[x-1][y+1]) ad.add(new int[] {x-1, y+1, d});
if(isValid(x-1,y) && !used[x-1][y]) ad.add(new int[] {x-1, y, d});
//if(isValid(x-1,y-1) && !used[x-1][y-1]) ad.add(new int[] {x-1, y-1, d});
}
int max = Integer.MIN_VALUE;
int maxx = 0, maxy = 0;
for(int i = 0; i<n; i++) {
for(int j = 0; j<m; j++) {
if(mind[i][j] > max) {
max = mind[i][j];
maxx = i+1;
maxy = j+1;
}
}
}
out.println(maxx + " " + maxy);
out.flush();
}
private static boolean isValid(int x, int y) {
return x>=0 && x<n && y>=0 && y<m;
}
/////////////////////////////////////////////////
// pre - written
/////////////////////////////////////////////////
private static void println(Object o) throws Exception {
System.out.println(o);
}
private static void exit(Object o) throws Exception {
println(o);
exit();
}
private static void exit() {
System.exit(0);
}
/////////////////////////////////
}
| cubic | 35_C. Fire Again | CODEFORCES |
//package round35;
import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class C {
Scanner in;
PrintWriter out;
// String INPUT = "3 3 1 1 1";
String INPUT = "";
void solve()
{
int n = ni();
int m = ni();
int k = ni();
int[] x = new int[k];
int[] y = new int[k];
for(int i = 0;i < k;i++){
x[i] = ni() - 1;
y[i] = ni() - 1;
}
int max = -1;
int maxi = -1;
int maxj = -1;
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
int min = Integer.MAX_VALUE;
for(int l = 0;l < k;l++){
min = Math.min(min, Math.abs(x[l] - i) + Math.abs(y[l] - j));
}
if(min > max){
max = min;
maxi = i;
maxj = j;
}
}
}
out.println((maxi+1) + " " + (maxj+1));
}
void run() throws Exception
{
in = INPUT.isEmpty() ? new Scanner(new File("input.txt")) : new Scanner(INPUT);
out = INPUT.isEmpty() ? new PrintWriter("output.txt") : new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception
{
new C().run();
}
int ni() { return Integer.parseInt(in.next()); }
void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); }
static String join(int[] a, int d){StringBuilder sb = new StringBuilder();for(int v : a){sb.append(v + d + " ");}return sb.toString();}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
ArrayList<ArrayList<Integer>> fire = new ArrayList<ArrayList<Integer>>();
while (k-- != 0) {
ArrayList<Integer> t = new ArrayList<Integer>();
t.add(sc.nextInt());
t.add(sc.nextInt());
fire.add(t);
}
int maxI = 0, maxJ = 0, maxManhatten = -1;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++){
int curManhatten = Integer.MAX_VALUE;
for(int u = 0; u < fire.size(); u++)
curManhatten = Math.min(curManhatten, manhatten(i, j, fire.get(u).get(0), fire.get(u).get(1)));
if(curManhatten > maxManhatten){
maxManhatten = curManhatten;
maxI = i;
maxJ = j;
}
}
out.print(maxI + " " + maxJ);
out.flush();
out.close();
}
private static int manhatten(int i, int j, Integer a, Integer b) {
return Math.abs(i - a) + Math.abs(j - b);
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class practice {
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main(String[] args) throws IOException {
Reader scn=new Reader("input.txt");
PrintWriter out = new PrintWriter(new File("output.txt"));
int n=scn.nextInt(),m=scn.nextInt(),k=scn.nextInt();
int[][] inf=new int[k][2];
for(int i=0;i<k;i++){
inf[i][0]=scn.nextInt();inf[i][1]=scn.nextInt();
}
int ans=0,x=1,y=1;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
int temp=Integer.MAX_VALUE;
for(int l=0;l<k;l++){
temp=Math.min(temp, Math.abs(i-inf[l][0])+Math.abs(j-inf[l][1]));
}
if(temp>ans){
ans=temp;x=i;y=j;
}
}
}
out.print(x + " " + y);
out.close();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
*
*
* 3 2 3 5
* -2 -1 4 -1 2 7 3
*
* 10 1 -10617 30886 -7223 -63085 47793 -61665 -14614 60492 16649 -58579 3 8 1
* 10 4 7 1 7 3 7
*
* 22862 -34877
*
* @author pttrung
*/
public class C_Round_35_Div2 {
public static long MOD = 1000000007;
static int[] X = {0, 1, 0, -1};
static int[] Y = {1, 0, -1, 0};
static int[][][] dp;
public static void main(String[] args) throws FileNotFoundException {
PrintWriter out = new PrintWriter(new FileOutputStream(new File(
"output.txt")));
//PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[][] map = new int[n][m];
LinkedList<Point> q = new LinkedList();
int reX = -1;
int reY = -1;
for (int i = 0; i < k; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
reX = x;
reY = y;
map[x][y] = 1;
q.add(new Point(x, y));
}
while (!q.isEmpty()) {
Point p = q.poll();
// System.out.println(map[p.x][p.y] + " " + p.x + " " + p.y);
for (int i = 0; i < 4; i++) {
int x = p.x + X[i];
int y = p.y + Y[i];
if (x >= 0 && y >= 0 && x < n && y < m && map[x][y] == 0) {
map[x][y] = 1 + map[p.x][p.y];
if (map[x][y] > map[reX][reY]) {
reX = x;
reY = y;
}
q.add(new Point(x, y));
}
}
}
out.println((reX + 1) + " " + (reY + 1));
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return x - o.x;
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
// br = new BufferedReader(new InputStreamReader(System.in));
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author zodiacLeo
*/
public class Main
{
public static void main(String[] args)
{
InputStream inputStream;
try
{
inputStream = new FileInputStream("input.txt");
} catch (IOException e)
{
throw new RuntimeException(e);
}
OutputStream outputStream;
try
{
outputStream = new FileOutputStream("output.txt");
} catch (IOException e)
{
throw new RuntimeException(e);
}
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC
{
public void solve(int testNumber, FastScanner in, FastPrinter out)
{
int n = in.nextInt();
int m = in.nextInt();
int p = in.nextInt();
int[] x = new int[p];
int[] y = new int[p];
for (int i = 0; i < p; i++)
{
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int X = x[0];
int Y = y[0];
int D = -1;
for (int dx = 1; dx <= n; dx++)
{
int x1 = dx;
int y1 = 1;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int dx = 1; dx <= n; dx++)
{
int x1 = dx;
int y1 = m;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int dy = 1; dy <= m; dy++)
{
int x1 = 1;
int y1 = dy;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int dy = 1; dy <= m; dy++)
{
int x1 = n;
int y1 = dy;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int i = 1; i <= Math.min(m, n); i++)
{
int x1 = i;
int y1 = i;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int i = 1, ii = m; i <= n && ii >= 1; i++, ii--)
{
int x1 = i;
int y1 = ii;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
out.println(X + " " + Y);
}
}
static class FastScanner
{
public BufferedReader br;
public StringTokenizer st;
public FastScanner(InputStream is)
{
br = new BufferedReader(new InputStreamReader(is));
}
public FastScanner(File f)
{
try
{
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public String next()
{
while (st == null || !st.hasMoreElements())
{
String s = null;
try
{
s = br.readLine();
} catch (IOException e)
{
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
static class FastPrinter extends PrintWriter
{
public FastPrinter(OutputStream out)
{
super(out);
}
public FastPrinter(Writer out)
{
super(out);
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class C implements Runnable{
// SOLUTION!!!
// HACK ME PLEASE IF YOU CAN!!!
// PLEASE!!!
// PLEASE!!!
// PLEASE!!!
private final static Random rnd = new Random();
private final static String fileName = "";
private void solve() {
int n = readInt();
int m = readInt();
int k = readInt();
Point[] starts = readPointArray(k);
for (Point start : starts) {
start.x--;
start.y--;
}
Point furthest = bfs(n, m, starts);
out.println((furthest.x + 1) + " " + (furthest.y + 1));
}
private Point bfs(int n, int m, Point[] starts) {
final int INF = n * m + 1;
boolean[][] used = new boolean[n][m];
Queue<Integer> queue = new ArrayDeque<>();
for (Point start : starts) {
used[start.x][start.y] = true;
queue.add(start.x * m + start.y);
}
int last = -1;
while (queue.size() > 0) {
int from = queue.poll();
last = from;
int fromX = from / m, fromY = from % m;
for (int[] step : steps) {
int toX = fromX + step[0];
int toY = fromY + step[1];
if (!checkCell(toX, n, toY, m)) continue;
if (used[toX][toY]) continue;
used[toX][toY] = true;
queue.add(toX * m + toY);
}
}
return new Point(last / m, last % m);
}
/////////////////////////////////////////////////////////////////////
private final static boolean FIRST_INPUT_STRING = false;
private final static boolean MULTIPLE_TESTS = true;
private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private final static int MAX_STACK_SIZE = 128;
private final static boolean OPTIMIZE_READ_NUMBERS = false;
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeInit();
Locale.setDefault(Locale.US);
init();
if (ONLINE_JUDGE) {
solve();
} else {
do {
try {
timeInit();
solve();
time();
out.println();
} catch (NumberFormatException e) {
break;
} catch (NullPointerException e) {
if (FIRST_INPUT_STRING) break;
else throw e;
}
} while (MULTIPLE_TESTS);
}
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
private BufferedReader in;
private OutputWriter out;
private StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new C(), "", MAX_STACK_SIZE * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
private void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
////////////////////////////////////////////////////////////////
private long timeBegin;
private void timeInit() {
this.timeBegin = System.currentTimeMillis();
}
private void time(){
long timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
private void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
private String delim = " ";
private String readLine() {
try {
return in.readLine();
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private String readString() {
try {
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(readLine());
}
return tok.nextToken(delim);
} catch (NullPointerException e) {
return null;
}
}
/////////////////////////////////////////////////////////////////
private final char NOT_A_SYMBOL = '\0';
private char readChar() {
try {
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
private char[] readCharArray() {
return readLine().toCharArray();
}
private char[][] readCharField(int rowsCount) {
char[][] field = new char[rowsCount][];
for (int row = 0; row < rowsCount; ++row) {
field[row] = readCharArray();
}
return field;
}
/////////////////////////////////////////////////////////////////
private long optimizedReadLong() {
int sign = 1;
long result = 0;
boolean started = false;
while (true) {
try {
int j = in.read();
if (-1 == j) {
if (started) return sign * result;
throw new NumberFormatException();
}
if (j == '-') {
if (started) throw new NumberFormatException();
sign = -sign;
}
if ('0' <= j && j <= '9') {
result = result * 10 + j - '0';
started = true;
} else if (started) {
return sign * result;
}
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
}
private int readInt() {
if (!OPTIMIZE_READ_NUMBERS) {
return Integer.parseInt(readString());
} else {
return (int) optimizedReadLong();
}
}
private int[] readIntArray(int size) {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
private int[] readSortedIntArray(int size) {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
private int[] readIntArrayWithDecrease(int size) {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
private int[][] readIntMatrix(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
private long readLong() {
if (!OPTIMIZE_READ_NUMBERS) {
return Long.parseLong(readString());
} else {
return optimizedReadLong();
}
}
private long[] readLongArray(int size) {
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
private double readDouble() {
return Double.parseDouble(readString());
}
private double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
private BigInteger readBigInteger() {
return new BigInteger(readString());
}
private BigDecimal readBigDecimal() {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
private Point readPoint() {
int x = readInt();
int y = readInt();
return new Point(x, y);
}
private Point[] readPointArray(int size) {
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
@Deprecated
private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) {
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
private static class GraphBuilder {
final int size;
final List<Integer>[] edges;
static GraphBuilder createInstance(int size) {
List<Integer>[] edges = new List[size];
for (int v = 0; v < size; ++v) {
edges[v] = new ArrayList<>();
}
return new GraphBuilder(edges);
}
private GraphBuilder(List<Integer>[] edges) {
this.size = edges.length;
this.edges = edges;
}
public void addEdge(int from, int to) {
addDirectedEdge(from, to);
addDirectedEdge(to, from);
}
public void addDirectedEdge(int from, int to) {
edges[from].add(to);
}
public int[][] build() {
int[][] graph = new int[size][];
for (int v = 0; v < size; ++v) {
List<Integer> vEdges = edges[v];
graph[v] = castInt(vEdges);
}
return graph;
}
}
/////////////////////////////////////////////////////////////////////
private static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<C.IntIndexPair>() {
@Override
public int compare(C.IntIndexPair indexPair1, C.IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<C.IntIndexPair>() {
@Override
public int compare(C.IntIndexPair indexPair1, C.IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static IntIndexPair[] from(int[] array) {
IntIndexPair[] iip = new IntIndexPair[array.length];
for (int i = 0; i < array.length; ++i) {
iip[i] = new IntIndexPair(array[i], i);
}
return iip;
}
int value, index;
IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
int getRealIndex() {
return index + 1;
}
}
private IntIndexPair[] readIntIndexArray(int size) {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
private static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
private int precision;
private String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
OutputWriter(OutputStream out) {
super(out);
}
OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
int getPrecision() {
return precision;
}
void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
void printWithSpace(double d){
printf(formatWithSpace, d);
}
void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
private static class RuntimeIOException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -6463830523020118289L;
RuntimeIOException(Throwable cause) {
super(cause);
}
}
/////////////////////////////////////////////////////////////////////
//////////////// Some useful constants and functions ////////////////
/////////////////////////////////////////////////////////////////////
private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
private static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) {
return checkIndex(row, rowsCount) && checkIndex(column, columnsCount);
}
private static boolean checkIndex(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
private static boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
private static boolean checkBit(long mask, int bit){
return (mask & (1L << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
private static long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
private static Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
private static int[] getPrimes(int n) {
boolean[] used = new boolean[n];
used[0] = used[1] = true;
int size = 0;
for (int i = 2; i < n; ++i) {
if (!used[i]) {
++size;
for (int j = 2 * i; j < n; j += i) {
used[j] = true;
}
}
}
int[] primes = new int[size];
for (int i = 0, cur = 0; i < n; ++i) {
if (!used[i]) {
primes[cur++] = i;
}
}
return primes;
}
/////////////////////////////////////////////////////////////////////
private static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
private static long gcd(long a, long b) {
return (a == 0 ? b : gcd(b % a, a));
}
/////////////////////////////////////////////////////////////////////
private static class MultiSet<ValueType> {
public static <ValueType> MultiSet<ValueType> createMultiSet() {
Map<ValueType, Integer> multiset = new HashMap<>();
return new MultiSet<>(multiset);
}
private final Map<ValueType, Integer> multiset;
private int size;
public MultiSet(Map<ValueType, Integer> multiset) {
this.multiset = multiset;
this.size = 0;
}
public int size() {
return size;
}
public void inc(ValueType value) {
int count = get(value);
multiset.put(value, count + 1);
++size;
}
public void dec(ValueType value) {
int count = get(value);
if (count == 0) return;
if (count == 1) multiset.remove(value);
else multiset.put(value, count - 1);
--size;
}
public int get(ValueType value) {
Integer count = multiset.get(value);
return (count == null ? 0 : count);
}
}
/////////////////////////////////////////////////////////////////////
private static class IdMap<KeyType> extends HashMap<KeyType, Integer> {
/**
*
*/
private static final long serialVersionUID = -3793737771950984481L;
public IdMap() {
super();
}
int getId(KeyType key) {
Integer id = super.get(key);
if (id == null) {
super.put(key, id = size());
}
return id;
}
}
/////////////////////////////////////////////////////////////////////
private static int[] castInt(List<Integer> list) {
int[] array = new int[list.size()];
for (int i = 0; i < array.length; ++i) {
array[i] = list.get(i);
}
return array;
}
private static long[] castLong(List<Long> list) {
long[] array = new long[list.size()];
for (int i = 0; i < array.length; ++i) {
array[i] = list.get(i);
}
return array;
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
public class A_GENERAL {
// for fast output printing : use printwriter or stringbuilder
// remember to close pw using pw.close()
static StringBuilder sb = new StringBuilder();
static long seive_size = (long) 1e6;
static String alpha = "abcdefghijklmnopqrstuvwxyz";
static ArrayList<Integer> primes = new ArrayList<>();
static boolean[] seive_set = new boolean[(int) seive_size+1];
static int n, m, k;
static ArrayList<Integer>[] adj;
static boolean[] vis;
static ArrayDeque<Integer> q = new ArrayDeque<>();
static final long MOD = 998244353;
static int[] dx = new int[] {1, 0, -1, 0, 1, -1, 1, -1};
static int[] dy = new int[] {0, 1, 0, -1, -1, 1, 1, -1};
static long[][] arr;
static int[] rank;
static int[] parent;
static int[] s;
static long[] a;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
// MyScanner sc = new MyScanner();
Scanner sc = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter("output.txt");
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
ArrayDeque<iPair> qq = new ArrayDeque<>();
boolean[][] vis = new boolean[n+1][m+1];
for(int i = 0; i < k; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
qq.add(new iPair(u, v));
vis[u][v] = true;
}
iPair last = null;
while(!qq.isEmpty()) {
iPair pp = qq.poll();
int i = pp.f;
int j = pp.s;
if(isValid(i-1, j) && !vis[i-1][j]) {
qq.add(new iPair(i-1, j));
vis[i-1][j] = true;
}
if(isValid(i+1, j) && !vis[i+1][j]) {
qq.add(new iPair(i+1, j));
vis[i+1][j] = true;
}
if(isValid(i, j-1) && !vis[i][j-1]) {
qq.add(new iPair(i, j-1));
vis[i][j-1] = true;
}
if(isValid(i, j+1) && !vis[i][j+1]) {
qq.add(new iPair(i, j+1));
vis[i][j+1] = true;
}
last = pp;
}
out.println(last.f + " " + last.s);
sc.close();
out.close();
}
public static boolean isValid(int i, int j) {
if(i < 1 || i > n || j < 1 || j > m) return false;
return true;
}
public static class Triplet implements Comparable<Triplet> {
int x;
int y;
int z;
Triplet(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int compareTo(Triplet o) {
return Integer.compare(this.x, o.x);
}
}
public static class iPair implements Comparable<iPair> {
int f;
int s;
iPair(int f, int s) {
this.f = f;
this.s = s;
}
public int compareTo(iPair o) {
return Integer.compare(this.f, o.f);
}
}
public static class Pair implements Comparable<Pair>{
long f;
long s;
Pair(long f, long s) {
this.f = f;
this.s = s;
}
public int compareTo(Pair o) {
return Long.compare(this.f, o.f);
}
}
public static void init(int n) {
adj = new ArrayList[n+1];
vis = new boolean[n+1];
parent = new int[n+1];
rank = new int[n+1];
for(int i = 0; i <= n; i++) {
adj[i] = new ArrayList<>();
parent[i] = i;
rank[i] = 0;
}
}
// print string "s" multiple times
// prefer to use this function for multiple printing
public static String mp(String s, int times) {
return String.valueOf(new char[times]).replace("\0", s);
}
// take log with base 2
public static long log2(long k) {
return 63-Long.numberOfLeadingZeros(k);
}
// using lambda function for sorting
public static void lambdaSort() {
Arrays.sort(arr, (a, b) -> Double.compare(a[0], b[0]));
}
// (n choose k) = (n/k) * ((n-1) choose (k-1))
public static long choose(long n, long k) {
return (k == 0) ? 1 : (n*choose(n-1, k-1))/k;
}
// just for keeping gcd function for other personal purposes
public static long gcd(long a, long b) {
return (a == 0) ? b : gcd(b%a, a);
}
public static long max(long... as) {
long max = Long.MIN_VALUE;
for (long a : as) max = Math.max(a, max);
return max;
}
public static long min(int... as) {
long min = Long.MAX_VALUE;
for (long a : as) min = Math.min(a, min);
return min;
}
public static long modpow(long x, long n, long mod) {
if(n == 0) return 1%mod;
long u = modpow(x, n/2, mod);
u = (u*u)%mod;
if(n%2 == 1) u = (u*x)%mod;
return u;
}
// ======================= binary search (lower and upper bound) =======================
public static int lowerBound(long[] a, int x) {
int lo = 0;
int hi = a.length-1;
int ans = -1;
while(lo <= hi) {
int mid = (lo+hi)/2;
if(x < a[mid]) {
hi = mid-1;
} else if(x > a[mid]) {
lo = mid+1;
} else if(lo != hi) {
hi = mid-1; // for first occurrence
ans = mid;
} else {
return mid;
}
}
return ans;
}
public static int upperBound(long[] a, long x) {
int lo = 0;
int hi = a.length-1;
int ans = -1;
while(lo <= hi) {
int mid = (lo+hi)/2;
if(x < a[mid]) {
hi = mid-1;
} else if(x > a[mid]) {
lo = mid+1;
} else if(lo != hi) {
lo = mid+1; // for last occurrence
ans = mid;
} else {
return mid;
}
}
return ans;
}
// ================================================================
// ================== SEIVE OF ERATOSTHENES =======================
// Complexity : O(N * log(log(N))) ( almost O(N) )
public static void generatePrimes() {
// set.add(0);
// set.add(1);
Arrays.fill(seive_set, true);
seive_set[0] = false;
seive_set[1] = false;
for(int i = 2; i <= seive_size; i++) {
if(seive_set[i]) {
for(long j = (long) i*i; j <= seive_size; j+=i)
seive_set[(int)j] = false;
primes.add(i);
}
}
}
public static boolean isPrime(long N) {
if(N <= seive_size) return seive_set[(int)N];
for (int i = 0; i < (int)primes.size(); i++)
if (N % primes.get(i) == 0) return false;
return true;
}
// ===========================================================
// ================ Permutation of String ====================
public static void permute(String str) {
permute(str, 0, str.length()-1);
}
public static void permute(String str, int l, int r)
{
if (l == r)
System.out.println(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r);
str = swap(str,l,i);
}
}
}
public static String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
// Union-find
// static int[] parent, rank;
// public static void makeSet(int n) {
//
// parent = new int[n+1];
// rank = new int[n+1];
// for(int i = 1; i <= n; i++) {
// parent[i] = i;
// rank[i] = 0;
// }
// }
public static int find(int u) {
if(parent[u] == u) return u;
int v = find(parent[u]);
parent[u] = v;
return v;
}
public static boolean connected(int u, int v) {
return find(u) == find(v);
}
public static void Union(int u, int v) {
int x = find(u); //root of u
int y = find(v); //root of v
if(x == y) return;
if(rank[x] == rank[y]) {
parent[y] = x;
rank[x]++;
}
else if(rank[x] > rank[y]) {
parent[y] = x;
}
else {
parent[x] = y;
}
}
// public static int dijkstra(int x, int y) {
// int[] dist = new int[n+1];
// Arrays.fill(dist, Integer.MAX_VALUE);
// PriorityQueue<Node> q = new PriorityQueue<>();
// q.add(new Node(x, 0));
// dist[x] = 0;
// while(!q.isEmpty()) {
// Node node = q.poll();
// int u = node.key;
// if(u == y) {
// break;
// }
// for(int v : res[u]) {
// if(dist[v] > dist[u]+count[u]) {
// dist[v] = dist[u] + count[u];
// q.add(new Node(v, dist[v]));
// }
// }
// }
// if(dist[y] == Integer.MAX_VALUE) {
// return -1;
// }
// return dist[y];
// }
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}}
return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
String nextLine(){String str = "";
try {str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
int[] nextIntArray(int n, int delta) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt() + delta;
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class A {
static int dx[] = { 1, -1, 0, 0 };
static int dy[] = { 0, 0, 1, -1 };
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner("input.txt");
PrintWriter out = new PrintWriter("output.txt");
int n = sc.nextInt(), m = sc.nextInt();
int[][] grid = new int[n][m];
for (int[] i : grid)
Arrays.fill(i, -1);
Queue<Pair> q = new LinkedList<>();
int k = sc.nextInt();
for (int i = 0; i < k; i++) {
int x = sc.nextInt() - 1, y = sc.nextInt() - 1;
grid[x][y] = 0;
q.add(new Pair(x, y));
}
Pair p = new Pair(-1, -1);
while (!q.isEmpty()) {
p = q.poll();
for (int i = 0; i < dx.length; i++) {
int tx = p.x + dx[i], ty = p.y + dy[i];
if (tx >= 0 && tx < n && ty >= 0 && ty < m && grid[tx][ty] == -1) {
grid[tx][ty] = grid[p.x][p.y] + 1;
q.add(new Pair(tx, ty));
}
}
}
out.println(p);
out.flush();
out.close();
}
static class Pair {
int x, y;
public Pair(int a, int b) {
x = a;
y = b;
}
public String toString() {
return x + 1 + " " + (y + 1);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String r) throws FileNotFoundException {
br = new BufferedReader(new FileReader(r));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.List;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Problem {
public static Pair solve(Forest f, List<Pair> queue){
Pair current = null, next = null;
int index = 0;
while(queue.size() > 0){
current = queue.remove(0);
index = f.desk[current.x][current.y];
if(current.x>0){
next = new Pair(current.x-1,current.y);
if(f.desk[next.x][next.y]==0){
f.desk[next.x][next.y] = index+1;
queue.add(next);
}
}
if(current.x<f.N-1){
next = new Pair(current.x+1,current.y);
if(f.desk[next.x][next.y]==0){
f.desk[next.x][next.y] = index+1;
queue.add(next);
}
}
if(current.y>0){
next = new Pair(current.x,current.y-1);
if(f.desk[next.x][next.y]==0){
f.desk[next.x][next.y] = index+1;
queue.add(next);
}
}
if(current.y<f.M-1){
next = new Pair(current.x,current.y+1);
if(f.desk[next.x][next.y]==0){
f.desk[next.x][next.y] = index+1;
queue.add(next);
}
}
}
return f.findMax();
}
public static void main(String[] args){
String buffer = null;
StringTokenizer st = null;
Forest f = null;
List<Pair> pairs = new LinkedList<Pair>();
Integer N,M,K,x,y;
try {
BufferedReader in = new BufferedReader(
new FileReader("input.txt")
);
FileWriter out = new FileWriter("output.txt");
buffer = in.readLine();
st = new StringTokenizer(buffer);
N = new Integer(st.nextToken());
M = new Integer(st.nextToken());
f = new Forest(N,M);
buffer = in.readLine();
st = new StringTokenizer(buffer);
K = new Integer(st.nextToken());
buffer = in.readLine();
st = new StringTokenizer(buffer);
for(int i = 0; i<K; i++){
x = new Integer(st.nextToken());
y = new Integer(st.nextToken());
f.desk[x-1][y-1] = 1;
pairs.add(new Pair(x-1,y-1));
}
Pair res = solve(f,pairs);
out.write(res.toString());
out.flush();
} catch (Exception e) {
}
}
}
class Pair {
public Pair(int i, int j){
x = i;
y = j;
}
public String toString(){
return (x+1) + " " + (y+1);
}
public int x;
public int y;
}
class Forest {
public Forest(int n, int m){
N = n;
M = m;
desk = new int[N][M];
}
public Pair findMax(){
Pair max = new Pair(0,0);
for(int i = 0; i<N; i++){
for(int j = 0; j<M; j++){
if(desk[i][j]>desk[max.x][max.y]){
max.x = i;
max.y = j;
}
}
}
return max;
}
public int N;
public int M;
public int[][] desk;
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class FireAgain {
Scanner in;
PrintWriter out;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
new FireAgain().run();
}
void run() throws IOException {
in = new Scanner(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
solve();
in.close();
out.close();
}
private void solve() {
// TODO Auto-generated method stub
int N = in.nextInt();
int M = in.nextInt();
int[][] burn = new int[N + 1][M + 1];
int K = in.nextInt();
int[] qx = new int[N * M];
int[] qy = new int[N * M];
int first = 0;
int last = 0;
for (int i = 0; i < K; i ++){
qx[last] = in.nextInt();
qy[last] = in.nextInt();
burn[qx[last]][qy[last]] = 1;
last ++;
}
while (first < last){
int x = qx[first];
int y = qy[first];
if (x - 1 > 0 && burn[x - 1][y] == 0){
burn[x - 1][y] = 1;
qx[last] = x - 1;
qy[last] = y;
last ++;
}
if (y - 1 > 0 && burn[x][y - 1] == 0){
burn[x][y - 1] = 1;
qx[last] = x;
qy[last] = y - 1;
last ++;
}
if (x + 1 <= N && burn[x + 1][y] == 0){
burn[x + 1][y] = 1;
qx[last] = x + 1;
qy[last] = y;
last ++;
}
if (y + 1 <= M && burn[x][y + 1] == 0){
burn[x][y + 1] = 1;
qx[last] = x;
qy[last] = y + 1;
last ++;
}
first ++;
}
out.println(qx[last - 1] + " " + qy[last - 1]);
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class FireAgain {
static int n;
static int m;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader r = new BufferedReader(new FileReader("input.txt"));
String s = r.readLine();
String[] sp = s.split(" ");
n = new Integer(sp[0]);
m = new Integer(sp[1]);
boolean[][] v = new boolean[n][m];
r.readLine();
s = r.readLine();
sp = s.split(" ");
Queue<Integer> q = new LinkedList<Integer>();
for (int i = 0; i < sp.length; i += 2) {
v[new Integer(sp[i]) - 1][new Integer(sp[i + 1]) - 1] = true;
q.add(new Integer(sp[i]) - 1);
q.add(new Integer(sp[i + 1]) - 1);
}
int[] dx = { 1, -1, 0, 0 };
int[] dy = { 0, 0, 1, -1 };
int lx = -1;
int ly = -1;
while (!q.isEmpty()) {
int x = q.remove();
int y = q.remove();
lx = x;
ly = y;
for (int i = 0; i < dy.length; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (valid(nx, ny) && !v[nx][ny]) {
v[nx][ny] = true;
q.add(nx);
q.add(ny);
}
}
}
lx++;
ly++;
BufferedWriter wr=new BufferedWriter(new FileWriter("output.txt"));
wr.write(""+lx + " " + ly);
wr.newLine();
wr.close();
}
private static boolean valid(int nx, int ny) {
return nx >= 0 && nx < n && ny >= 0 && ny < m;
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import static java.lang.Math.*;
import java.io.*;
import java.math.*;
import java.util.*;
public class Solution implements Runnable {
public static void main(String... strings) throws InterruptedException {
new Thread(new Solution()).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String next() throws Exception {
if (st == null || !st.hasMoreElements())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(next());
}
double nextDouble() throws Exception {
return Double.parseDouble(next());
}
long nextLong() throws Exception {
return Long.parseLong(next());
}
@Override
public void run() {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
solve();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
out.close();
}
}
int n, m, k, xor = 0;
boolean[][] used;
HashSet<Long> [] set;
void solve() throws Exception {
n = nextInt();
m = nextInt();
k = nextInt();
used = new boolean[n][m];
set = new HashSet[2];
for(int i = 0; i < 2; set[i++] = new HashSet<Long>());
for(int i = 0; i < k; i++){
int x = nextInt()-1, y = nextInt()-1;
used[x][y] = true;
set[0].add(10000L*x + y);
}
for (;;xor ^= 1){
set[xor^1].clear();
int ansx = -1, ansy = -1;
for (long i : set[xor]){
int x = (int)(i/10000), y = (int)(i%10000);
if (ansx < 0){
ansx = x+1;
ansy = y+1;
}
add(x+1, y);
add(x-1, y);
add(x, y+1);
add(x, y-1);
}
if (set[xor^1].size() == 0){
out.println(ansx + " " + ansy);
break;
}
}
}
public void add(int x, int y){
if (!( x >= 0 && y >= 0 && x < n && y < m && !used[x][y])) return;
set[xor^1].add(10000L*x + y);
used[x][y] = true;
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader br;
static PrintWriter out;
static StringTokenizer st;
static int[][] moves = new int[][]{{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
static boolean correct(int x, int y, int n, int m) {
return (x >= 0 && x < n && y >= 0 && y < m);
}
static void solve() throws Exception {
int n = nextInt();
int m = nextInt();
int k = nextInt();
int[][] order = new int[n][m];
boolean[][] used = new boolean[n][m];
Queue<Integer[]> q = new LinkedList<>();
Set<String> set = new HashSet<String>();
for(int i = 0; i < k; i++) {
int x = nextInt() - 1;
int y = nextInt() - 1;
order[x][y] = 1;
used[x][y] = true;
q.add(new Integer[] {x, y});
set.add(x + "" + y);
}
while(!q.isEmpty()) {
Integer[] v = q.remove();
for(int[] move : moves) {
int x = v[0] + move[0];
int y = v[1] + move[1];
// if(set.contains(x + "" + y)) {
// continue;
// }
if(correct(x, y, n, m) && !used[x][y]) {
q.add(new Integer[] {x, y});
used[x][y] = true;
order[x][y] = order[v[0]][v[1]] + 1;
}
}
}
int max = Integer.MIN_VALUE;
int maxI = -1;
int maxJ = -1;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(order[i][j] > max) {
max = order[i][j];
maxI = i;
maxJ = j;
}
}
}
maxI++;
maxJ++;
out.println(maxI + " " + maxJ);
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public static void main(String[] args) {
try {
InputStream input = System.in;
OutputStream output = System.out;
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
out = new PrintWriter(new PrintStream(new File("output.txt")));
solve();
out.close();
br.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main1 {
static int dr[] = { 0, 0, 1, -1 };
static int dc[] = { 1, -1, 0, 0 };
static boolean isValid(int r, int c) {
if (r >= n || r < 0 || c >= m || c < 0)
return false;
return true;
}
static int grid[][];
static int n, m;
public static void main(String[] args) throws IOException {
FastReader input = new FastReader();
PrintWriter out = new PrintWriter("output.txt");
n = input.nextInt();
m = input.nextInt();
grid = new int[n][m];
int k = input.nextInt();
for (int i = 0; i < n; i++) {
Arrays.fill(grid[i], Integer.MAX_VALUE);
}
Queue<Pair> q = new LinkedList<Pair>();
for (int i = 0; i < k; i++) {
int x = input.nextInt() - 1;
int y = input.nextInt() - 1;
q.add(new Pair(x, y));
grid[x][y] = 0;
while (!q.isEmpty()) {
Pair cur = q.poll();
for (int j = 0; j < dr.length; j++) {
int r = cur.x;
int c = cur.y;
int nr = r + dr[j];
int nc = c + dc[j];
int dist = grid[r][c] + 1;
if (isValid(nr, nc) && grid[nr][nc] > dist) {
grid[nr][nc] = dist;
q.add(new Pair(nr, nc));
}
}
}
}
int max = -1;
int x = -1;
int y = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] > max) {
max = grid[i][j];
x = i + 1;
y = j + 1;
}
}
}
out.println(x + " " + y);
out.flush();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File("input.txt")));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
String str = "";
str = br.readLine();
return str;
}
}
static class con {
static int IINF = (int) 1e9;
static int _IINF = (int) -1e9;
static long LINF = (long) 1e15;
static long _LINF = (long) -1e15;
static double EPS = 1e-9;
}
static class Triple implements Comparable<Triple> {
int x;
int y;
int z;
Triple(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int compareTo(Triple o) {
if (x == o.x && y == o.y)
return z - o.z;
if (x == o.x)
return y - o.y;
return x - o.x;
}
}
static class Pair implements Comparable<Pair> {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if (x == o.x)
return y - o.y;
return x - o.x;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
static void shuffle(int[] a) {
for (int i = 0; i < a.length; i++) {
int r = i + (int) (Math.random() * (a.length - i));
int tmp = a[r];
a[r] = a[i];
a[i] = tmp;
}
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
public static int n,m;
public static void main(String[] arg) {
FastScanner scan = null;
PrintWriter out = null;
try{
scan = new FastScanner(new FileInputStream("input.txt"));
out = new PrintWriter(new FileOutputStream("output.txt"));
}catch(FileNotFoundException e){
scan = new FastScanner(System.in);
out = new PrintWriter(System.out);
}
n = scan.nextInt();
m = scan.nextInt();
int k = scan.nextInt();
int[][] board = new int[n+1][m+1];
String[] ins = scan.nextLine().split(" ",-1);
List<Integer> ps = new ArrayList<Integer>();
for(int i = 0; i < 2 * k; i += 2){
int a = Integer.parseInt(ins[i]);
int b = Integer.parseInt(ins[i+1]);
board[a][b] = 1;
ps.add(a * 2001 + b);
}
int retx = 1, rety = 1;
int[] dx = {0,1,0,-1};
int[] dy = {1,0,-1,0};
while(true){
boolean find = false;
List<Integer> ps2 = new ArrayList<Integer>();
for(Integer p : ps){
int i = p / 2001;
int j = p % 2001;
for(int q = 0; q < 4; q++){
int nx = i + dx[q];
int ny = j + dy[q];
if(in(nx,ny) && board[nx][ny] == 0){
board[nx][ny] = 1;
retx = nx;
rety = ny;
find = true;
ps2.add(nx * 2001 + ny);
}
}
board[i][j] = 2;
}
ps = ps2;
if(!find) break;
}
out.println(retx + " " + rety);
out.close();
}
public static boolean in(int i, int j){
return (1 <= i && i <= n) && (1 <= j && j <= m);
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream is) {
try {
br = new BufferedReader(new InputStreamReader(is));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
return null;
}
}
return st.nextToken();
}
String nextLine() {
try {
return br.readLine();
}
catch (Exception e) {
return null;
}
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.valueOf(next());
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
* Created by mostafa on 10/7/17.
*/
public class FireAgain {
static int n, m, k;
static int inf = (int) 1e9;
static class Pair {
int x, y;
Pair(int a, int b) {
x = a; y = b;
}
}
static int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1};
static boolean valid(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < m;
}
static int[][] bfs(int[] xs, int[] ys) {
int[][] dist = new int[n][m];
for(int i = 0; i < n; i++)
Arrays.fill(dist[i], inf);
Queue<Pair> q = new LinkedList<>();
for(int i = 0; i < k; i++) {
dist[xs[i]][ys[i]] = 0;
q.add(new Pair(xs[i], ys[i]));
}
while(!q.isEmpty()) {
Pair p = q.remove();
for(int d = 0; d < 4; d++) {
int nx = p.x + dx[d], ny = p.y + dy[d];
if(valid(nx, ny) && dist[nx][ny] == inf) {
dist[nx][ny] = dist[p.x][p.y] + 1;
q.add(new Pair(nx, ny));
}
}
}
return dist;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt();
int[] xs = new int[k], ys = new int[k];
for(int i = 0; i < k; i++) {
xs[i] = sc.nextInt() - 1; ys[i] = sc.nextInt() - 1;
}
int[][] dist = bfs(xs, ys);
int x = 0, y = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(dist[i][j] > dist[x][y]) {
x = i; y = j;
}
x++; y++;
PrintWriter out = new PrintWriter("output.txt");
out.println(x + " " + y);
out.flush();
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
String next() throws IOException {
while(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.Point;
import java.io.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Main{
static class Run implements Runnable{
//TODO parameters
final boolean consoleIO = false;
final String inFile = "input.txt";
final String outFile = "output.txt";
int n,m,k;
int[][] field;
boolean[][] visited;
LinkedList<Point> queue;
int[][] steps = {{0,1},{1,0},{0,-1},{-1,0}};
void wave() {
for(Point p:queue)
visited[p.y][p.x] = true;
while(!queue.isEmpty()) {
Point cur = queue.removeFirst();
for(int i = 0; i < steps.length; ++i) {
Point tmp = new Point(cur.x+steps[i][0],cur.y+steps[i][1]);
if(ok(tmp)&&!visited[tmp.y][tmp.x]) {
queue.add(tmp);
visited[tmp.y][tmp.x] = true;
field[tmp.y][tmp.x] = field[cur.y][cur.x]+1;
}
}
}
}
boolean ok(Point p) {
return p.x>=0 && p.y>=0 && p.x<n && p.y<m;
}
@Override
public void run() {
n = nextInt();
m = nextInt();
k = nextInt();
queue = new LinkedList<Point>();
for(int i = 0; i < k; ++i)
queue.add(new Point(nextInt()-1,nextInt()-1));
field = new int[m][n];
visited = new boolean[m][n];
wave();
Point maxP = new Point(0,0);
int maxV = Integer.MIN_VALUE;
for(int i = 0; i < m; ++i)
for(int j = 0; j < n; ++j)
if(field[i][j] > maxV) {
maxV = field[i][j];
maxP = new Point(j,i);
}
print((maxP.x+1)+" "+(maxP.y+1));
close();
}
//=========================================================================================================================
BufferedReader in;
PrintWriter out;
StringTokenizer strTok;
Run() {
if (consoleIO) {
initConsoleIO();
}
else {
initFileIO();
}
}
void initConsoleIO() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
void initFileIO() {
try {
in = new BufferedReader(new FileReader(inFile));
out = new PrintWriter(new FileWriter(outFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
void close() {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
float nextFloat() {
return Float.parseFloat(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
String nextLine() {
try {
return in.readLine();
} catch (IOException e) {
return "__NULL";
}
}
boolean hasMoreTokens() {
return (strTok == null) || (strTok.hasMoreTokens());
}
String nextToken() {
while (strTok == null || !strTok.hasMoreTokens()) {
String line;
try {
line = in.readLine();
strTok = new StringTokenizer(line);
} catch (IOException e) {
e.printStackTrace();
}
}
return strTok.nextToken();
}
void cout(Object o){
System.out.println(o);
}
void print(Object o) {
out.write(o.toString());
}
void println(Object o) {
out.write(o.toString() + '\n');
}
void printf(String format, Object... args) {
out.printf(format, args);
}
String sprintf(String format, Object... args) {
return MessageFormat.format(format, args);
}
}
static class Pair<A, B> {
A a;
B b;
A f() {
return a;
}
B s() {
return b;
}
Pair(A a, B b) {
this.a = a;
this.b = b;
}
Pair(Pair<A, B> p) {
a = p.f();
b = p.s();
}
}
public static void main(String[] args) throws IOException {
Run run = new Run();
Thread thread = new Thread(run);
thread.run();
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.Collection;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Objects;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Queue;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CFireAgain solver = new CFireAgain();
solver.solve(1, in, out);
out.close();
}
static class CFireAgain {
private int n;
private int m;
private int K;
private boolean[][] vis;
private Queue<Util.Pair<Integer>> queue = new LinkedList<>();
private Util.Pair<Integer> p;
private boolean isValid(int x, int y) {
return x >= 1 && x <= n && y >= 1 && y <= m && !vis[x][y];
}
private void bfs() {
while (!queue.isEmpty()) {
p = queue.poll();
if (isValid(p.x + 1, p.y)) {
queue.offer(new Util.Pair<>(p.x + 1, p.y));
vis[p.x + 1][p.y] = true;
}
if (isValid(p.x - 1, p.y)) {
queue.offer(new Util.Pair<>(p.x - 1, p.y));
vis[p.x - 1][p.y] = true;
}
if (isValid(p.x, p.y + 1)) {
queue.offer(new Util.Pair<>(p.x, p.y + 1));
vis[p.x][p.y + 1] = true;
}
if (isValid(p.x, p.y - 1)) {
queue.offer(new Util.Pair<>(p.x, p.y - 1));
vis[p.x][p.y - 1] = true;
}
}
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
m = in.nextInt();
K = in.nextInt();
vis = new boolean[n + 1][m + 1];
for (int i = 0; i < K; i++) {
int a = in.nextInt(), b = in.nextInt();
vis[a][b] = true;
queue.offer(new Util.Pair<>(a, b));
}
bfs();
out.println(p.x + " " + p.y);
out.flush();
}
}
static class OutputWriter {
private final PrintWriter writer;
private ArrayList<String> res = new ArrayList<>();
private StringBuilder sb = new StringBuilder("");
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(Object... objects) {
for (int i = 0; i < objects.length; i++) {
sb.append(objects[i]);
}
res.add(sb.toString());
sb = new StringBuilder("");
}
public void close() {
// writer.flush();
writer.close();
}
public void flush() {
for (String str : res) writer.printf("%s\n", str);
res.clear();
sb = new StringBuilder("");
}
}
static class Util {
public static class Pair<T> {
public T x;
public T y;
public Pair(T x, T y) {
this.x = x;
this.y = y;
}
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Util.Pair)) return false;
Util.Pair<T> pair = (Util.Pair<T>) obj;
return this.x == pair.x && this.y == pair.y;
}
public String toString() {
return ("(" + this.x + "," + this.y + ")");
}
public int hashCode() {
return Objects.hash(x, y);
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public InputReader(FileInputStream file) {
this.stream = file;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = (res << 3) + (res << 1) + c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.Point;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class Contest35_3 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("input.txt"));
String[] s = in.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
int k = Integer.parseInt(in.readLine());
s = in.readLine().split(" ");
Point[] inp = new Point[k];
int p = 0;
for (int i = 0; i < k; i++) {
inp[i] = new Point(Integer.parseInt(s[p++]),
Integer.parseInt(s[p++]));
}
int max = -1;
int maxx = -1;
int maxy = -1;
int i;
int j, dist;
for (i = 1; i <= n; i++) {
for (j = 1; j <= m; j++) {
dist = 1000000;
for (int l = 0; l < inp.length; l++) {
dist = Math.min(
Math.abs(inp[l].x - i) + Math.abs(inp[l].y - j),
dist);
}
if (dist > max) {
max = dist;
maxx = i;
maxy = j;
}
}
}
String res = maxx + " " + maxy + "\n";
FileWriter out = new FileWriter(new File("output.txt"));
out.append(res);
out.flush();
out.close();
}
} | cubic | 35_C. Fire Again | CODEFORCES |
/**
* Created by IntelliJ IDEA.
* User: Taras_Brzezinsky
* Date: 9/16/11
* Time: 1:27 PM
* To change this template use File | Settings | File Templates.
*/
import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Queue;
import java.util.StringTokenizer;
public class TaskC extends Thread {
public TaskC() {
try {
this.input = new BufferedReader(new FileReader("input.txt"));
this.output = new PrintWriter("output.txt");
this.setPriority(Thread.MAX_PRIORITY);
} catch (Throwable e) {
System.exit(666);
}
}
private void solve() throws Throwable {
int n = nextInt();
int m = nextInt();
int k = nextInt();
Queue<Integer> qX = new ArrayDeque<Integer>();
Queue<Integer> qY = new ArrayDeque<Integer>();
boolean [][]was = new boolean[n][m];
for (int i = 0; i < k; ++i) {
int x = nextInt() - 1, y = nextInt() - 1;
qX.add(x);
qY.add(y);
was[x][y] = true;
}
int lastX = -1, lastY = -1;
while (!qX.isEmpty()) {
lastX = qX.poll();
lastY = qY.poll();
for (int i = 0; i < dx.length; ++i) {
int nextX = lastX + dx[i], nextY = lastY + dy[i];
if (nextX < n && nextY < m && nextX >= 0 && nextY >= 0 && !was[nextX][nextY]) {
qX.add(nextX);
qY.add(nextY);
was[nextX][nextY] = true;
}
}
}
++lastX;
++lastY;
output.println(lastX + " " + lastY);
}
public void run() {
try {
solve();
} catch (Throwable e) {
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(666);
} finally {
output.flush();
output.close();
}
}
public static void main(String[] args) {
new TaskC().start();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private String nextToken() throws IOException {
while (tokens == null || !tokens.hasMoreTokens()) {
tokens = new StringTokenizer(input.readLine());
}
return tokens.nextToken();
}
static final int PRIME = 3119;
static final int[]dx = {1, -1, 0, 0}, dy = {0, 0, -1, 1};
private BufferedReader input;
private PrintWriter output;
private StringTokenizer tokens = null;
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class incendio {
void dbg(Object...os) { System.err.println(Arrays.deepToString(os)); }
static StringTokenizer _stk; static BufferedReader input; static PrintWriter output;
static String next(){return _stk.nextToken();} static int nextInt(){return Integer.parseInt(next());}
static String readln()throws IOException {String l=input.readLine();_stk=l==null?null:new StringTokenizer(l," ");return l;}
public static void main(String[] args) throws IOException {
input = new BufferedReader(new FileReader("input.txt"));
output = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
new incendio();
output.close();
}
incendio() throws IOException {
readln();
M = nextInt(); N = nextInt();
readln();
final int K = nextInt();
int xf[]=new int[K], yf[]=new int[K];
readln();
for(int i=0; i<K; i++) {
xf[i]=nextInt();
yf[i]=nextInt();
}
int best=-1, xbest=0, ybest=0;
for(int i=1; i<=M; i++) {
for(int j=1; j<=N; j++) {
int dist=Integer.MAX_VALUE;
for(int k=0; k<K; k++) {
dist = Math.min(dist, Math.abs(i-xf[k])+Math.abs(j-yf[k]));
}
if(dist>best) {
best=dist;
xbest=i;
ybest=j;
}
}
}
output.println(xbest+" "+ybest);
}
int M, N;
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
long MAX = 100000L, MOD = 1000000007L, INF = (long) 1e18;
boolean isValid(int x, int y, int n, int m){
return x>=0 && y>=0 && x<n && y<m;
}
void solve(int TC) throws Exception {
helper hp = new helper(MOD, (int)MAX);
hp.initIO("input.txt", "output.txt");
int n = hp.nextInt(), m = hp.nextInt();
boolean[][] a = new boolean[n][m];
int k = hp.nextInt();
ArrayDeque<int[]> q = new ArrayDeque<>();
for(int i=0;i<k;i++){
int x = hp.nextInt() - 1;
int y = hp.nextInt() - 1;
a[x][y] = true;
q.add(new int[]{x,y});
}
int lastX = 0,lastY = 0;
int[] dx = new int[]{1,-1,0,0};
int[] dy = new int[]{0,0,1,-1};
while(!q.isEmpty()){
int[] X = q.pollFirst();
for(int i=0;i<4;i++){
int x = X[0] + dx[i];
int y = X[1] + dy[i];
if(isValid(x,y,n,m) && !a[x][y]){
a[x][y] = true;
lastX = x;
lastY = y;
q.add(new int[]{x,y});
}
}
}
hp.println((lastX+1) + " " + (lastY+1)); hp.flush();
}
boolean TestCases = false;
public static void main(String[] args) throws Exception { new Main().run(); }
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
static void dbg(Object... o){System.err.println(Arrays.deepToString(o));}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
int T = TestCases ? ni() : 1;
for(int t=1;t<=T;t++) solve(t);
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
void p(Object o) { out.print(o); }
void pn(Object o) { out.println(o); }
void pni(Object o) { out.println(o);out.flush(); }
double PI = 3.141592653589793238462643383279502884197169399;
int ni() {
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-') {
minus = true;
b = readByte();
}
while(true) {
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nl() {
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-') {
minus = true;
b = readByte();
}
while(true) {
if(b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
double nd() { return Double.parseDouble(ns()); }
char nc() { return (char)skip(); }
int BUF_SIZE = 1024 * 8;
byte[] inbuf = new byte[BUF_SIZE];
int lenbuf = 0, ptrbuf = 0;
int readByte() {
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
} return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))) {
sb.appendCodePoint(b); b = readByte();
} return sb.toString();
}
char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
} return n == p ? buf : Arrays.copyOf(buf, p);
}
void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}
class helper {
final long MOD;
final int MAXN;
final Random rnd;
public helper(long mod, int maxn) {
MOD = mod;
MAXN = maxn;
rnd = new Random();
}
static final int BUFSIZE = 1 << 20;
static byte[] buf;
static int index, total;
static InputStream in;
static BufferedWriter bw;
public void initIO(InputStream is, OutputStream os) {
try {
in = is;
bw = new BufferedWriter(new OutputStreamWriter(os));
buf = new byte[BUFSIZE];
} catch (Exception e) {
}
}
public void initIO(String inputFile, String outputFile) {
try {
in = new FileInputStream(inputFile);
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFile)));
buf = new byte[BUFSIZE];
} catch (Exception e) {
e.printStackTrace();
}
}
private int scan() throws Exception {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0)
return -1;
}
return buf[index++];
}
public String next() throws Exception {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan())
sb.append((char) c);
return sb.toString();
}
public int nextInt() throws Exception {
int c, val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public long nextLong() throws Exception {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+')
c = scan();
for (; c >= '0' && c <= '9'; c = scan())
val = (val << 3) + (val << 1) + (c & 15);
return neg ? -val : val;
}
public long pow(long base, long exp, long MOD) {
base %= MOD;
long ret = 1;
while (exp > 0) {
if ((exp & 1) == 1) ret = ret * base % MOD;
base = base * base % MOD;
exp >>= 1;
}
return ret;
}
public void println(Object a) throws Exception {
bw.write(a.toString()+"\n");
}
public void print(Object a) throws Exception {
bw.write(a.toString());
}
public void flush() throws Exception {
bw.flush();
}
public static int[] sieve;
public static ArrayList<Integer> primes;
public void setSieve() {
primes = new ArrayList<>();
sieve = new int[MAXN];
int i, j;
for (i = 2; i < MAXN; ++i)
if (sieve[i] == 0) {
primes.add(i);
for (j = i; j < MAXN; j += i) {
sieve[j] = i;
}
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class Solution implements Runnable {
Scanner input;
PrintWriter output;
private void solve() throws Exception
{
int n = nextInt();
int m = nextInt();
int k = nextInt();
int[] r = new int[k];
int[] c = new int[k];
for (int i = 0; i < k; i++)
{
r[i] = nextInt();
c[i] = nextInt();
}
int best = -1;
int bestr = -1;
int bestc = -1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
int d = n + m;
for (int q = 0; q < k; q++)
{
d = Math.min(d, Math.abs(i - r[q]) + Math.abs(j - c[q]));
}
if (d < best) continue;
best = d;
bestr = i;
bestc = j;
}
}
out(bestr + " " + bestc);
}
private int nextInt() throws Exception
{
return input.nextInt();
}
private void out(String s)
{
output.println(s);
}
public void run() {
try {
solve();
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
output.close();
}
}
public Solution() throws IOException {
input = new Scanner(new FileReader("input.txt"));
output = new PrintWriter("output.txt");
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new Thread(new Solution()).start();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.Point;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args)throws IOException, URISyntaxException {
Reader.init(new FileInputStream("input.txt"));
StringBuilder s=new StringBuilder();
boolean[][]vis=new boolean[Reader.nextInt()][Reader.nextInt()];
int k=Reader.nextInt(),r,c;
Queue<Point>q=new LinkedList<Point>();
while(k-->0) {
r=Reader.nextInt()-1;
c=Reader.nextInt()-1;
vis[r][c]=true;
q.add(new Point(r,c));
}
Point end=null;
int[]x={0,0,1,-1},y={1,-1,0,0};
int a,b,i;
while(!q.isEmpty()) {
end=q.poll();
for(i=0;i<4;i++) {
a=end.x+x[i];
b=end.y+y[i];
if(a>=0&&b>=0&&a<vis.length&&b<vis[a].length&&!vis[a][b]) {
vis[a][b]=true;
q.add(new Point(a,b));
}
}
}
s.append(end.x+1).append(' ').append(end.y+1);
PrintWriter p=new PrintWriter("output.txt");
p.println(s);
p.close();
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) throws UnsupportedEncodingException {
reader = new BufferedReader(
new InputStreamReader(input, "UTF-8") );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException {
return reader.readLine();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;
public class C {
static class Struct {
int x, y, count;
public Struct(int xx, int yy, int c) {
x = xx;
y = yy;
count = c;
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new FileReader("input.txt"));
int n = sc.nextInt();
int m = sc.nextInt();
FileWriter fw=new FileWriter("output.txt");
boolean[][] grid = new boolean[n][m];
int[] dx = new int[] { 1, 0, -1, 0 };
int[] dy = new int[] { 0, -1, 0, 1 };
int k = sc.nextInt();
LinkedList<Struct> a = new LinkedList<Struct>();
for (int i = 0; i < k; i++) {
a.add(new Struct(sc.nextInt() - 1, sc.nextInt() - 1, 0));
}
int max = Integer.MIN_VALUE, maxX = -1, maxY = -1;
while (!a.isEmpty()) {
Struct tmp = a.remove();
if (grid[tmp.x][tmp.y] == true)
continue;
grid[tmp.x][tmp.y] = true;
if (tmp.count > max) {
max = tmp.count;
maxX = tmp.x;
maxY = tmp.y;
}
for (int i = 0; i < 4; i++) {
int nx = tmp.x + dx[i];
int ny = tmp.y + dy[i];
if (nx < n && nx >= 0 && ny < m && ny >= 0) {
if (grid[nx][ny] == false) {
a.add(new Struct(nx, ny, tmp.count + 1));
}
}
}
}
fw.write((maxX + 1) + " " + (maxY + 1)+"\n");
System.out.println((maxX + 1) + " " + (maxY + 1));
fw.flush();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.ArrayDeque;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author MaxHeap
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FireAgain solver = new FireAgain();
solver.solve(1, in, out);
out.close();
}
static class FireAgain {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int INF = 10000000;
int[][] g = new int[n][m];
for (int[] temp : g) Arrays.fill(temp, -1);
ArrayDeque<IntPair> q = new ArrayDeque<>();
for (int i = 0; i < k; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
g[x][y] = 0;
q.add(new IntPair(x, y));
}
while (!q.isEmpty()) {
IntPair cur = q.poll();
int x = cur.getFirst();
int y = cur.getSecond();
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0 || Math.abs(i) + Math.abs(j) != 1) continue;
int xx = x + i;
int yy = y + j;
if (xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
if (g[xx][yy] != -1) continue;
g[xx][yy] = g[x][y] + 1;
q.add(new IntPair(xx, yy));
}
}
}
int ans = 0, x = -1, y = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] >= ans) {
ans = g[i][j];
x = i + 1;
y = j + 1;
}
}
}
out.println(x + " " + y);
}
}
static class IntPair implements Comparable<IntPair> {
int first;
int second;
public IntPair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(IntPair a) {
if (second == a.second) {
return Integer.compare(first, a.first);
}
return Integer.compare(second, a.second);
}
public String toString() {
return "<" + first + ", " + second + ">";
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IntPair a = (IntPair) o;
if (first != a.first) return false;
return second == a.second;
}
public int hashCode() {
int result = first;
result = 31 * result + second;
return result;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
static class FastReader {
BufferedReader reader;
StringTokenizer st;
public FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String line = reader.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
public class Main {
public static void main(String[] args) throws IOException {
new Thread(null, new Runnable() {
public void run() {
try {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {}
new Main().run();
} catch (IOException e) {
e.printStackTrace();
}
}
}, "1", 1L << 24).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
int N;
int M;
boolean[][] used;
Queue<Integer> queue;
int[] dx = { -1, 0, 1, 0 };
int[] dy = { 0, -1, 0, 1 };
int ans = -1;
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter("output.txt");
N = nextInt();
M = nextInt();
used = new boolean [N][M];
queue = new ArrayDeque<Integer> (N * M);
for (int K = nextInt(); K --> 0; )
addState(nextInt() - 1, nextInt() - 1);
while (!queue.isEmpty()) {
int cv = queue.poll();
int cx = cv / M;
int cy = cv % M;
for (int d = 0; d < dx.length; d++) {
int nx = cx + dx[d];
int ny = cy + dy[d];
if (0 <= nx && nx < N && 0 <= ny && ny < M && !used[nx][ny])
addState(nx, ny);
}
}
out.println((1 + ans / M) + " " + (1 + ans % M));
out.close();
}
void addState(int x, int y) {
used[x][y] = true;
queue.add(ans = code(x, y));
}
int code(int x, int y) {
return x * M + y;
}
String nextToken() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null) {
return true;
}
st = new StringTokenizer(s);
}
return false;
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
// package Practice1.CF35;
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class CF035C {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(new File("input.txt")/*System.in*/);
int n = s.nextInt();
int m = s.nextInt();
int k = s.nextInt();
// pair[] arr = new pair[n];
Queue<pair> q = new LinkedList<>();
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
boolean[][] visited = new boolean[n][m];
for (int i = 0; i < k; i++) {
int x = s.nextInt() - 1;
int y = s.nextInt() - 1;
visited[x][y] = true;
pair p = new pair(x,y);
// arr[i] = p;
q.add(p);
}
q.add(null);
int[] dx = {0,0,1,-1};
int[] dy = {1,-1,0,0};
int ansX = q.peek().x;
int ansY = q.peek().y;
while(true){
if(q.peek() == null){
q.poll();
q.add(null);
}
pair p = q.poll();
if(p == null){
break;
}
for (int i = 0; i < 4; i++) {
if(isValid(p.x + dx[i],p.y+dy[i],n,m) && !visited[p.x + dx[i]][p.y+dy[i]]){
q.add(new pair(p.x + dx[i],p.y+dy[i]));
ansX = p.x + dx[i];
ansY = p.y + dy[i];
visited[ansX][ansY] = true;
}
}
}
out.println((ansX+1) + " " + (ansY+1));
out.close();
}
public static boolean isValid(int x, int y,int n, int m){
return x >= 0 && x < n && y >= 0 && y < m;
}
private static class pair{
int x;
int y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.util.*;
import java.io.*;
public class SolutionC{
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(new File("input.txt"));
PrintWriter output = new PrintWriter("output.txt");
int N = sc.nextInt();
int M = sc.nextInt();
int K = sc.nextInt();
int[] x = new int[K];
int[] y = new int[K];
for(int i = 0 ; i < K ; i++){
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
int max = -1, max_x = -1, max_y = -1;
for(int i = 1 ; i <= N ; i++){
for(int j = 1 ; j <= M ; j++){
int min = Integer.MAX_VALUE;
for(int k = 0 ; k < K ; k++){
min = Math.min(min, Math.abs(x[k] - i) + Math.abs(y[k] - j));
}
if(min > max){
max = min;
max_x = i;
max_y = j;
}
}
}
output.println(max_x + " " + max_y);
output.flush();
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class j
{
public static void main(String a[])throws IOException
{
BufferedReader b = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
int l=0,x2=0,x=0,y1=0,y=0,max=-1,min=100000,x1=0,n=0,j=0,k=0,p=0,m=0,i=0;
String s;
s=b.readLine();
StringTokenizer c=new StringTokenizer(s);
n=Integer.parseInt(c.nextToken());
m=Integer.parseInt(c.nextToken());
k=Integer.parseInt(b.readLine());
int e[][]=new int[k][2];
s=b.readLine();
StringTokenizer z=new StringTokenizer(s);
for(i=0;i<k;i++)
{
e[i][0]=Integer.parseInt(z.nextToken());
e[i][1]=Integer.parseInt(z.nextToken());
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
for(l=0;l<k;l++)
{
p=(int)Math.abs(e[l][0]-i)+(int)Math.abs(e[l][1]-j);
if(p<min)
{
min=p;
x1=i;
y1=j;
}
}
if(min>max)
{
max=min;
x=x1;
y=y1;
}
min=100000;
}
}
out.print(x+" "+y);
out.close();
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.Point;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
public class C {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new FileReader(new File("input.txt")));
PrintWriter out = new PrintWriter(new File("output.txt"));
int n = in.nextInt();
int m = in.nextInt();
int[][] T = new int[n][m];
int k = in.nextInt();
int[] X = new int[k];
int[] Y = new int[k];
for (int i = 0; i < k; i++) {
X[i] = in.nextInt() - 1;
Y[i] = in.nextInt() - 1;
}
int max = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
int min = Integer.MAX_VALUE;
for (int ii = 0; ii < k; ii++)
min = Math.min(min,
Math.abs(i - X[ii]) + Math.abs(j - Y[ii]));
max = Math.max(max, T[i][j] = min);
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (T[i][j] == max) {
out.println((i + 1) + " " + (j + 1));
out.flush();
return;
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
public class ProblemC {
static int[] dx = {1, 0, 0, -1};
static int[] dy = {0, 1, -1, 0};
public static void main(String[] args) throws IOException {
BufferedReader s = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
// BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
// PrintWriter out = new PrintWriter(System.out);
String[] nm = s.readLine().split(" ");
int n = Integer.valueOf(nm[0]);
int m = Integer.valueOf(nm[1]);
int k = Integer.valueOf(s.readLine());
int[][] dp = new int[n][m];
for (int i = 0 ; i < n ; i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE);
}
String[] st = s.readLine().split(" ");
int[][] trees = new int[k][2];
for (int l = 0 ; l < k ; l++) {
trees[l][0] = Integer.valueOf(st[l*2])-1;
trees[l][1] = Integer.valueOf(st[l*2+1])-1;
}
int maxtime = -1;
int max_x = -1;
int max_y = -1;
for (int i = 0 ; i < n ; i++) {
for (int j = 0 ; j < m ; j++) {
int minDist = n+m;
for (int l = 0 ; l < k ; l++) {
minDist = Math.min(minDist, Math.abs(i - trees[l][0]) + Math.abs(j - trees[l][1]));
}
if (maxtime < minDist) {
maxtime = minDist;
max_x = i+1;
max_y = j+1;
}
}
}
out.println(max_x + " " + max_y);
out.flush();
}
public static void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Problem implements Runnable {
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tok = new StringTokenizer("");
private void init() throws FileNotFoundException {
Locale.setDefault(Locale.US);
String fileName = "";
/* if (ONLINE_JUDGE && fileName.isEmpty()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
if (fileName.isEmpty()) {*/
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
/* } else {
in = new BufferedReader(new FileReader(fileName + ".in"));
out = new PrintWriter(fileName + ".out");
/* }
}*/
}
String readString() {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() {
return Integer.parseInt(readString());
}
long readLong() {
return Long.parseLong(readString());
}
double readDouble() {
return Double.parseDouble(readString());
}
int[] readIntArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = readInt();
}
return a;
}
public static void main(String[] args) {
//new Thread(null, new _Solution(), "", 128 * (1L << 20)).start();
new Problem().run();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
@Override
public void run() {
try {
timeBegin = System.currentTimeMillis();
init();
solve();
out.close();
time();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
int[][] dist;
int n, m;
P v;
ArrayDeque<P> q = new ArrayDeque<>();
private void solve() throws IOException {
n = readInt();
m = readInt();
int k = readInt();
dist = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
dist[i][j] = -1;
for (int i = 0; i < k; i++) {
int x = readInt() - 1, y = readInt() - 1;
dist[x][y] = 0;
q.add(new P(x, y));
}
bfs();
out.println(v.x + 1 + " " + (v.y + 1));
}
public void bfs() {
int[] dx = {0, 1, 0, -1};
int[] dy = {1, 0, -1, 0};
while (!q.isEmpty()) {
v = q.poll();
for (int i = 0; i < 4; i++) {
int nx = v.x + dx[i];
int ny = v.y + dy[i];
if (inside(nx, ny) && dist[nx][ny] == -1) {
q.add(new P(nx, ny));
dist[nx][ny] = dist[v.x][v.y] + 1;
}
}
}
}
public boolean inside(int x, int y) {
if (x < n && y < m && x >= 0 && y >= 0) {
return true;
}
return false;
}
}
class P {
int x, y;
public P(int x, int y) {
this.x = x;
this.y = y;
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import javax.annotation.processing.SupportedSourceVersion;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(new FileReader("input.txt")); // new InputReader(inputStream);
PrintWriter out = new PrintWriter("output.txt"); //new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(in, out);
out.close();
}
private static class TaskB {
static final long max = 1000000000000000000L;
static final double eps = 0.0000001;
static final long mod = 1000000007;
static int N, M, K;
static long X, Y;
static boolean F[][][];
static int D[][];
void solve(InputReader in, PrintWriter out) throws IOException {
N = in.nextInt();
M = in.nextInt();
K = in.nextInt();
F = new boolean[K][N][M];
D = new int[N][M];
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
D[i][j] = Integer.MAX_VALUE;
List<Pair> list = new ArrayList<>();
for (int i = 0; i < K; i++) {
list.add(new Pair(in.nextInt() - 1, in.nextInt() - 1));
}
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
for (int k = 0; k < K; k++)
D[i][j] = Math.min(D[i][j], Math.abs(list.get(k).X - i) + Math.abs(list.get(k).Y - j));
int res = Integer.MIN_VALUE;
for (int j = 0; j < N; j++)
for (int k = 0; k < M; k++)
if (D[j][k] > res) {
X = j + 1;
Y = k + 1;
res = D[j][k];
}
out.println(X + " " + Y);
}
void bfs(int K, Pair P) {
Queue<Pair> Q = new LinkedList<>();
F[K][P.X][P.Y] = true;
D[P.X][P.Y] = 0;
Q.add(P);
while (!Q.isEmpty()) {
P = Q.poll();
int X = P.X;
int Y = P.Y;
if (check(X - 1, Y) && !F[K][X - 1][Y]) {
F[K][X - 1][Y] = true;
if (D[X - 1][Y] > D[X][Y] + 1) {
D[X - 1][Y] = D[X][Y] + 1;
Q.add(new Pair(X - 1, Y));
}
}
if (check(X + 1, Y) && !F[K][X + 1][Y]) {
F[K][X + 1][Y] = true;
if (D[X + 1][Y] > D[X][Y] + 1) {
D[X + 1][Y] = D[X][Y] + 1;
Q.add(new Pair(X + 1, Y));
}
}
if (check(X, Y - 1) && !F[K][X][Y - 1]) {
F[K][X][Y - 1] = true;
if (D[X][Y - 1] > D[X][Y] + 1) {
D[X][Y - 1] = D[X][Y] + 1;
Q.add(new Pair(X, Y - 1));
}
}
if (check(X, Y + 1) && !F[K][X][Y + 1]) {
F[K][X][Y + 1] = true;
if (D[X][Y + 1] > D[X][Y] + 1) {
D[X][Y + 1] = D[X][Y] + 1;
Q.add(new Pair(X, Y + 1));
}
}
}
}
boolean check(int X, int Y) {
return !(X < 0 || X >= N || Y < 0 || Y >= M);
}
class Pair {
int X, Y;
Pair(int X, int Y) {
this.X = X;
this.Y = Y;
}
}
long gcd(long A, long B) {
if (B == 0) return A;
return gcd(B, A % B);
}
boolean isPrime(long n) {
if (n <= 1 || n > 3 && (n % 2 == 0 || n % 3 == 0))
return false;
for (long i = 5, j = 2; i * i <= n; i += j, j = 6 - j)
if (n % i == 0)
return false;
return true;
}
boolean isEqual(double A, double B) {
return Math.abs(A - B) < eps;
}
double dist(double X1, double Y1, double X2, double Y2) {
return Math.sqrt((X1 - X2) * (X1 - X2) + (Y1 - Y2) * (Y1 - Y2));
}
boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
long pow(long A, long B, long MOD) {
if (B == 0) {
return 1;
}
if (B == 1) {
return A;
}
long val = pow(A, B / 2, MOD);
if (B % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * A % MOD) % MOD;
}
}
}
private static class InputReader {
StringTokenizer st;
BufferedReader br;
public InputReader(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public InputReader(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() {
while (st == null || !st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
public boolean ready() {
try {
return br.ready();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.util.*;
import java.io.*;
public class Main {
public static void main(String [] args) throws IOException{
Scanner in = new Scanner(new FileInputStream("input.txt"));
//Scanner in = new Scanner(System.in);
File file = new File("output.txt");
FileOutputStream fos = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
int N = in.nextInt();
int M = in.nextInt();
int K = in.nextInt();
int [][] fireTime = new int[N][M];
for (int i=0; i<K; i++){
int x = in.nextInt()-1;
int y = in.nextInt()-1;
fireTime[x][y] = -1;
for (int j=1; j<=x+y; j++){
for (int p=0; p<=j; p++){
if (x-j+p >= 0 && y-p >=0 && (fireTime[x-j+p][y-p] == 0 || fireTime[x-j+p][y-p] > j)){
fireTime[x-j+p][y-p] = j;
}
}
}
for (int j=1; j<=x+M-1-y; j++){
for (int p=0; p<=j; p++){
if (x-j+p >= 0 && y+p < M && (fireTime[x-j+p][y+p] == 0 || fireTime[x-j+p][y+p] > j)){
fireTime[x-j+p][y+p] = j;
}
}
}
for (int j=1; j<=N-1-x+y; j++){
for (int p=0; p<j; p++){
if (x+j-p < N && y-p >= 0 && (fireTime[x+j-p][y-p] == 0 || fireTime[x+j-p][y-p] > j)){
fireTime[x+j-p][y-p] = j;
}
}
}
for (int j=1; j<=N-1-x+M-1-y; j++){
for (int p=0; p<=j; p++){
//System.out.println(j+" "+p);
if (x+j-p < N && y+p < M && (fireTime[x+j-p][y+p] == 0 || fireTime[x+j-p][y+p] > j)){
//System.out.println(j);
fireTime[x+j-p][y+p] = j;
}
}
}
}
int max = -1;
int tx = 1;
int ty = 1;
for (int i=0; i<N; i++){
for (int j=0; j<M; j++){
//System.out.print(fireTime[i][j]+" ");
if (fireTime[i][j] > max){
max = fireTime[i][j];
tx = i+1;
ty = j+1;
}
}
//System.out.println();
}
//System.out.println(tx+" "+ty);
String output = tx+" "+ty;
byte[] bA = output.getBytes();
fos.write(bA);
fos.flush();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.Collection;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Queue;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Nafiur Rahman Khadem Shafin 🙂
*/
public class Main {
public static void main (String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader (inputStream);
PrintWriter out = new PrintWriter (outputStream);
ProblemCFireAgain solver = new ProblemCFireAgain ();
solver.solve (1, in, out);
out.close ();
}
static class ProblemCFireAgain {
private static final byte[] dx = {-1, 0, 0, 1};
private static final byte[] dy = {0, -1, 1, 0};
private static int[][] lvl;
private static int max;
private static int n;
private static int m;
private static int k;
private static ProblemCFireAgain.Pair[] bgn;
private static ProblemCFireAgain.Pair res;
private static void bfs2d () {
Queue<ProblemCFireAgain.Pair> bfsq = new LinkedList<ProblemCFireAgain.Pair> ();
for (ProblemCFireAgain.Pair src : bgn) {
lvl[src.a][src.b] = 0;
bfsq.add (src);
}
while (!bfsq.isEmpty ()) {
ProblemCFireAgain.Pair op = bfsq.poll ();
int plvl = lvl[op.a][op.b];
// System.out.println ("ber hoise "+op+" "+plvl);
if (plvl>max) {
res = op;
max = plvl;
}
for (int i = 0; i<4; i++) {
int newX = op.a+dx[i];
int newY = op.b+dy[i];
// System.out.println (newX+" "+newY+" "+n+" "+m);
if (newX>0 && newX<=n && newY>0 && newY<=m && lvl[newX][newY] == -1) {
bfsq.add (new ProblemCFireAgain.Pair (newX, newY));
lvl[newX][newY] = (plvl+1);
// System.out.println ("dhukse "+newX+" "+newY);
}
}
}
}
public void solve (int testNumber, InputReader _in, PrintWriter _out) {
/*
* file input-output 😮. Multi source bfs. Same as snackdown problem.
* */
try (InputReader in = new InputReader (new FileInputStream ("input.txt"));
PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter ("output.txt")))) {
n = in.nextInt ();
m = in.nextInt ();
k = in.nextInt ();
bgn = new ProblemCFireAgain.Pair[k];
for (int i = 0; i<k; i++) {
bgn[i] = new ProblemCFireAgain.Pair (in.nextInt (), in.nextInt ());
}
max = Integer.MIN_VALUE;
lvl = new int[n+5][m+5];
for (int i = 0; i<n+4; i++) {
Arrays.fill (lvl[i], -1);
}
bfs2d ();
// System.out.println (max);
out.println (res);
} catch (Exception e) {
// e.printStackTrace ();
}
}
private static class Pair {
int a;
int b;
Pair (int a, int b) {
this.a = a;
this.b = b;
}
public String toString () {
return a+" "+b;
}
public boolean equals (Object o) {
if (this == o) return true;
if (!(o instanceof ProblemCFireAgain.Pair)) return false;
ProblemCFireAgain.Pair pair = (ProblemCFireAgain.Pair) o;
return a == pair.a && b == pair.b;
}
public int hashCode () {
return Objects.hash (a, b);
}
}
}
static class InputReader implements AutoCloseable {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader (InputStream stream) {
reader = new BufferedReader (new InputStreamReader (stream));
tokenizer = null;
}
public String next () {
while (tokenizer == null || !tokenizer.hasMoreTokens ()) {
try {
String str;
if ((str = reader.readLine ()) != null) tokenizer = new StringTokenizer (str);
else return null;//to detect eof
} catch (IOException e) {
throw new RuntimeException (e);
}
}
return tokenizer.nextToken ();
}
public int nextInt () {
return Integer.parseInt (next ());
}
public void close () throws Exception {
reader.close ();
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class FireAgain {
Point coordinate;
Queue<Point> q = new LinkedList<Point>();
int m, n;
boolean[][] arr;
PrintStream out ;
void bfs(Point start) {
while (!q.isEmpty()) {
Point front = q.poll();
Point p = new Point();
p.x = front.x - 1;
p.y = front.y;
if (p.x >= 1 && p.x <= n && p.y <= m && p.y >= 1) {
if (!arr[p.x][p.y]) {
arr[p.x][p.y] = true;
q.add(p);
}
}
p = new Point();
p.x = front.x + 1;
p.y = front.y;
if (p.x >= 1 && p.x <= n && p.y <= m && p.y >= 1)
if (!arr[p.x][p.y]) {
arr[p.x][p.y] = true;
q.add(p);
}
p = new Point() ;
p.x = front.x;
p.y = front.y + 1;
if (p.x >= 1 && p.x <= n && p.y <= m && p.y >= 1)
if (!arr[p.x][p.y]) {
arr[p.x][p.y] = true;
q.add(p);
}
p = new Point() ;
p.x = front.x;
p.y = front.y - 1;
if (p.x >= 1 && p.x <= n && p.y <= m && p.y >= 1)
if (!arr[p.x][p.y]) {
arr[p.x][p.y] = true;
q.add(p);
}
if (q.size() == 0)
out.print(front.x + " " + front.y);
}
}
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
FireAgain fa = new FireAgain();
Scanner Scan = new Scanner(new FileInputStream("input.txt"));
fa.out = new PrintStream(new File("output.txt"));
fa.n = Scan.nextInt();
fa.m = Scan.nextInt();
int k = Scan.nextInt();
fa.arr = new boolean[2001][2001];
for (int i = 0; i < k; i++) {
fa.coordinate = new Point();
fa.coordinate.x = Scan.nextInt();
fa.coordinate.y = Scan.nextInt();
fa.q.add(fa.coordinate);
fa.arr[fa.coordinate.x][fa.coordinate.y] = true;
}
fa.bfs(fa.q.peek());
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
public static void mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int leftIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergeSort(a, leftIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
int[] leftArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
int mini = Integer.MAX_VALUE;
int maxi = Integer.MIN_VALUE;
int ans = 0;
int ans2 = 0;
int sum = 0;
void solve() throws IOException {
int n = readInt();
int m = readInt();
int maxi=0;
int [][] a = new int [n][m];
int k = readInt();
ArrayDeque<Point> dq = new ArrayDeque<Point> ();
Point p = new Point();
for (int i = 0; i<n; i++)
for (int j= 0; j<m; j++){
a[i][j]=Integer.MAX_VALUE;
}
for (int i = 0; i<k; i++){
int x = readInt()-1;
int y = readInt()-1;
p.x=x;
p.y=y;
dq.add(new Point(x,y));
a[x][y]=0;
}
while (!dq.isEmpty()){
Point v = dq.pollFirst();
Point u = new Point();
if (v.x-1!=-1) {
if (a[v.x-1][v.y]>a[v.x][v.y]+1){
a[v.x-1][v.y]=a[v.x][v.y]+1;
maxi=max(maxi,a[v.x-1][v.y]);
u.x=v.x-1;
u.y=v.y;
dq.add(new Point(u.x,u.y));
}
}
if (v.y-1!=-1) {
if (a[v.x][v.y-1]>a[v.x][v.y]+1){
a[v.x][v.y-1]=a[v.x][v.y]+1;
maxi=max(maxi,a[v.x][v.y-1]);
u.y=v.y-1;
u.x=v.x;
dq.add(new Point(u.x,u.y));
}
}
if (v.x+1!=n) {
if (a[v.x+1][v.y]>a[v.x][v.y]+1){
a[v.x+1][v.y]=a[v.x][v.y]+1;
maxi=max(maxi,a[v.x+1][v.y]);
u.x=v.x+1;
u.y=v.y;
dq.add(new Point(u.x,u.y));
}
}
if (v.y+1!=m) {
if (a[v.x][v.y+1]>a[v.x][v.y]+1){
a[v.x][v.y+1]=a[v.x][v.y]+1;
maxi=max(maxi,a[v.x][v.y+1]);
u.y=v.y+1;
u.x=v.x;
dq.add(new Point(u.x,u.y));
}
}
}
for (int i =0; i<n; i++)
for (int j =0; j<m; j++){
if (maxi==a[i][j]) {
out.print((i+1) + " " + (j+1));
return;
}
}
}
char c[];
void per (int left, int right){
if(left == right){
for (int i = 0; i<=right;i++){
out.print(c[i]);
}
out.println();
}
else {
for (int i = left; i <=right; i++){
char k = c[left];
c[left] = c[i];
c[i] = k;
per(left+1,right);
k = c[left];
c[left] = c[i];
c[i] = k;
}
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class C35
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static int n,m;
static class Pair
{
int x,y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
}
static boolean[][] burned;
static int[] dx={-1,0,1,0};
static int[] dy={0,-1,0,1};
static boolean isvalid(int x,int y)
{
return x>=0&&x<n&&y>=0&&y<m;
}
public static void main(String[] args) throws IOException
{
Scanner in = new Scanner("input.txt");
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
n=in.nextInt();
m=in.nextInt();
burned=new boolean[n][m];
int k=in.nextInt();
Queue<Pair> queue=new LinkedList<>();
Pair prev=null;
for(int i=0;i<k;i++)
{
int x=in.nextInt();
int y=in.nextInt();
burned[x-1][y-1]=true;
queue.add(prev=new Pair(x-1, y-1));
}
while(!queue.isEmpty())
{
Queue<Pair> tempqueue=new LinkedList<>();
for(Pair p : queue)
{
int x=p.x;
int y=p.y;
prev=p;
for(int i=0;i<4;i++)
{
if(isvalid(x+dx[i], y+dy[i])&&!burned[x+dx[i]][y+dy[i]])
{
tempqueue.add(new Pair(x+dx[i], y+dy[i]));
burned[x+dx[i]][y+dy[i]]=true;
}
}
}
queue=tempqueue;
}
out.printf("%d %d\n",(prev.x+1),(prev.y+1));
out.close();
}
public static long pow(long x, long n)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p))
{
if ((n & 1) != 0)
{
res = (res * p);
}
}
return res;
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class R035CRetry {
public void debug(Object... objects) { System.err.println(Arrays.deepToString(objects)); }
public static final int INF = 987654321;
public static final long LINF = 987654321987654321L;
public static final double EPS = 1e-9;
Scanner scanner;
PrintWriter out;
boolean[][] bss;
public R035CRetry() {
try {
this.scanner = new Scanner(new File("input.txt"));
this.out = new PrintWriter("output.txt");
} catch(FileNotFoundException ex) { ex.printStackTrace(); }
}
class Point implements Comparable<Point> {
int x, y, count;
Point(int x, int y) { this.x = x; this.y = y; }
public int hashCode() { return x * 17 + y; }
public boolean equals(Object o) {
if(!(o instanceof Point)) return false;
Point that = (Point)o;
return this.x == that.x && this.y == that.y;
}
public int compareTo(Point that) { return this.count - that.count; }
public String toString() { return "(" + x + ", " + y + ":" + count + ")"; }
}
int[] dx = new int[] { 0, 0, -1, 1 };
int[] dy= new int[] { -1, 1, 0, 0 };
int n, m;
Queue<Point> q;
Point bfs() {
int max = -INF;
Point p = null;
while(!q.isEmpty()) {
Point cur = q.remove();
if(max < cur.count) { max = cur.count; p = cur; }
for(int i=0; i<dx.length; i++) {
int nx = cur.x + dx[i];
int ny = cur.y + dy[i];
if(nx < 0 || nx >= n) { continue; }
if(ny < 0 || ny >= m) { continue; }
Point np = new Point(nx, ny);
if(bss[nx][ny] ) { continue; }
np.count = cur.count+1;
bss[nx][ny] = true;
q.add(np);
}
}
return p;
}
private void solve() {
this.n = scanner.nextInt();
this.m = scanner.nextInt();
this.bss = new boolean[n][m];
int k = scanner.nextInt();
q = new LinkedList<Point>();
for(int i=0; i<k; i++) {
int x = scanner.nextInt() - 1;
int y = scanner.nextInt() - 1;
Point init = new Point(x, y);
init.count = 1;
q.add(init);
bss[x][y] = true;
}
Point p = bfs();
out.println((p.x+1) + " " + (p.y+1));
}
private void finish() { this.out.close(); }
public static void main(String[] args) {
R035CRetry obj = new R035CRetry();
obj.solve();
obj.finish();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Watermelon {
static int[][] ans;static int n,m;static boolean[][] vis;
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(new File("input.txt"));
// Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter("output.txt");
int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt();
Queue<Integer> pq=new ArrayDeque<>();
boolean[] vis=new boolean[n*m];
for(int i=0;i<k;i++){
int r=sc.nextInt()-1,c=sc.nextInt()-1;
pq.add(m*r+c);
vis[m*r+c]=true;
}
sc.close();
int ans=0;
while(pq.size()!=0){
int x=pq.remove();
ans=x;
if(n!=1 && x%n==0){
if(x+m<n*m&&!vis[x+m]){
pq.add(x+m);
vis[x+m]=true;
}
if(x-m>=0&&!vis[x-m]){
pq.add(x-m);
vis[x-m]=true;
}
if(x+1<n*m&&!vis[x+1]){
pq.add(x+1);
vis[x+1]=true;
}
}
else if(n!=1 && (x+1)%n==0){
if(x+m<n*m&&!vis[x+m]){
pq.add(x+m);
vis[x+m]=true;
}
if(x-m>=0&&!vis[x-m]){
pq.add(x-m);
vis[x-m]=true;
}
if(x-1>=0&&!vis[x-1]){
pq.add(x-1);
vis[x-1]=true;
}
}
else{
if(x+m<n*m&&!vis[x+m]){
pq.add(x+m);
vis[x+m]=true;
}
if(x-m>=0&&!vis[x-m]){
pq.add(x-m);
vis[x-m]=true;
}
if(x-1>=0&&!vis[x-1]){
pq.add(x-1);
vis[x-1]=true;
}
if(x+1<n*m&&!vis[x+1]){
pq.add(x+1);
vis[x+1]=true;
}
}
}
pw.println((ans/m+1)+" "+(ans%m+1));
pw.close();
}
static class Reader{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.LinkedList;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter("output.txt");
String[] raw = in.readLine().split(" ");
int n = Integer.parseInt(raw[0]);
int m = Integer.parseInt(raw[1]);
int k = Integer.parseInt(in.readLine());
raw = in.readLine().split(" ");
boolean[][] map = new boolean[n][m];
LinkedList<Point> queue = new LinkedList<>();
for (int i = 0; i < k; i++) {
Point fireStarter = new Point(Integer.parseInt(raw[i * 2]) - 1, Integer.parseInt(raw[i * 2 + 1]) - 1);
queue.addLast(fireStarter);
}
int treesLeft = n * m;
while (true) {
Point firepoint = queue.removeFirst();
if (map[firepoint.x][firepoint.y])
continue;
treesLeft--;
map[firepoint.x][firepoint.y] = true;
if (treesLeft == 0) {
out.printf("%d %d", firepoint.x + 1, firepoint.y + 1);
out.flush();
return;
}
if (firepoint.x > 0 && !map[firepoint.x - 1][firepoint.y])
queue.add(new Point(firepoint.x - 1, firepoint.y));
if (firepoint.y > 0 && !map[firepoint.x][firepoint.y - 1])
queue.add(new Point(firepoint.x, firepoint.y - 1));
if (firepoint.x < n - 1 && !map[firepoint.x + 1][firepoint.y])
queue.add(new Point(firepoint.x + 1, firepoint.y));
if (firepoint.y < m - 1 && !map[firepoint.x][firepoint.y + 1])
queue.add(new Point(firepoint.x, firepoint.y + 1));
//
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// System.out.printf("%d ", map[i][j] ? 1 : 0);
// }
// System.out.println();
// }
// System.out.println("\n-------\n");
}
}
private static class Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.Point;
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import static java.lang.Integer.*;
import static java.lang.Math.*;
@SuppressWarnings("unused")
public class round35C {
static class state{
int x, y, time;
public state(int xx, int yy, int t){
x = xx;
y = yy;
time = t;
}
}
static int N,M;
static int [] dx = new int [] {1,-1,0,0};
static int [] dy = new int [] {0,0,1,-1};
static Queue<state> bfs = new LinkedList<round35C.state>();
public static Point runBFS(){
boolean [][] vis = new boolean [N + 1][M + 1];
int max = -(int)1e9;
int bestx = -1;
int besty = -1;
while(!bfs.isEmpty()){
state p = bfs.poll();
int x = p.x;
int y = p.y;
int time = p.time;
if(vis[x][y])
continue;
vis[x][y] = true;
if(time > max){
max = time;
bestx = x + 1;
besty = y + 1;
}
for(int i = 0 ; i < 4 ; ++i){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx < 0 || ny < 0 || nx >= N || ny >= M)
continue;
if(vis[nx][ny] == false)
bfs.offer(new state(nx, ny, time + 1));
}
}
return new Point(bestx, besty);
}
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter("output.txt");
String [] use = null;
use = br.readLine().split(" ");
N = parseInt(use[0]);
M = parseInt(use[1]);
int K = parseInt(br.readLine());
use = br.readLine().split(" ");
for(int i = 0 ; i < 2 * K ; i += 2){
int f = parseInt(use[i]) - 1;
int t = parseInt(use[i + 1]) - 1;
bfs.offer(new state(f, t, 0));
}
Point ans = runBFS();
out.println(ans.x + " " + ans.y);
out.flush();
out.close();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Solution implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
@Override
public void run() {
try {
init();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
long time = System.currentTimeMillis();
try {
solve();
} catch (Exception e) {
e.printStackTrace();
}
out.close();
//System.err.println(System.currentTimeMillis() - time);
}
private void init() throws FileNotFoundException {
String file = "123";
if (!file.equals("")) {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
public static void main(String[] args) {
new Thread(new Solution()).start();
}
private String readString() {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tok.nextToken();
}
private int readInt() {
return Integer.parseInt(readString());
}
int[] counts = new int[1000];
private long readLong() {
return Long.parseLong(readString());
}
private void solve() {
int n = readInt()+2;
int m = readInt()+2;
boolean[][] graph = new boolean[n][m];
for (int i = 0; i < n; i++) {
graph[i][m-1] = true;
graph[i][0] = true;
}
for (int i = 0; i < m; i++) {
graph[n-1][i] = true;
graph[0][i] = true;
}
int k = readInt();
int inFire = 0;
Queue<Point> q = new ArrayDeque<>();
for (int i = 0; i < k; i++) {
int x = readInt();
int y = readInt();
Point p = new Point(x, y);
graph[x][y] = true;
q.add(p);
}
while (!q.isEmpty()) {
Point current = q.poll();
inFire++;
if(!graph[current.x+1][current.y]) {
graph[current.x+1][current.y] = true;
q.add(new Point(current.x+1, current.y));
}
if(!graph[current.x-1][current.y]) {
graph[current.x-1][current.y] = true;
q.add(new Point(current.x-1, current.y));
}
if(!graph[current.x][current.y+1]) {
graph[current.x][current.y+1] = true;
q.add(new Point(current.x, current.y+1));
}
if(!graph[current.x][current.y-1]) {
graph[current.x][current.y-1] = true;
q.add(new Point(current.x, current.y-1));
}
if(q.isEmpty()) {
out.print(current.x+" "+current.y);
return;
}
}
}
class Point{
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.StringTokenizer;
import static java.lang.Math.abs;
/**
* 35C
*
* @author artyom
*/
public class FireAgain implements Runnable {
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tok;
private void solve() throws IOException {
int n = nextInt(), m = nextInt();
int[][] sources = readIntMatrix(nextInt(), 2);
int max = -1, maxI = 0, maxJ = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int min = Integer.MAX_VALUE;
for (int[] source : sources) {
int dist = abs(source[0] - i) + abs(source[1] - j);
if (dist < min) {
min = dist;
}
}
if (min > max) {
max = min;
maxI = i;
maxJ = j;
}
}
}
out.print((maxI + 1) + " " + (maxJ + 1));
}
//--------------------------------------------------------------
public static void main(String[] args) {
new FireAgain().run();
}
@Override
public void run() {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
tok = null;
solve();
in.close();
out.close();
} catch (IOException e) {
System.exit(0);
}
}
private String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private int[][] readIntMatrix(int n, int m) throws IOException {
int[][] mx = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mx[i][j] = nextInt() - 1;
}
}
return mx;
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int R = sc.nextInt();
int C = sc.nextInt();
int K = sc.nextInt();
int[] x = new int[K];
int[] y = new int[K];
for (int i = 0; i < K; i++) {
x[i] = sc.nextInt();
y[i] = sc.nextInt();
}
int best = -1;
int bestX = 0;
int bestY = 0;
for (int r = 1; r <= R; r++) for (int c = 1; c <= C; c++) {
int here = R + C;
for (int i = 0; i < K; i++) {
int t = abs(r - x[i]) + abs(c - y[i]);
here = min(here, t);
}
if (best < here){
best = here;
bestX = r;
bestY = c;
}
}
out.println(bestX + " " + bestY);
}
void print(int[] a) {
out.print(a[0]);
for (int i = 1; i < a.length; i++) out.print(" " + a[i]);
out.println();
}
static void tr(Object... os) {
System.err.println(deepToString(os));
}
public static void main(String[] args) throws Exception {
new Main().run();
}
MyScanner sc = null;
PrintWriter out = null;
public void run() throws Exception {
// sc = new MyScanner(System.in);
// out = new PrintWriter(System.out);
sc = new MyScanner(new FileInputStream(new File("input.txt")));
out = new PrintWriter(new File("output.txt"));
for (;sc.hasNext();) {
solve();
out.flush();
}
out.close();
}
class MyScanner {
String line;
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public void eat() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
line = reader.readLine();
if (line == null) {
tokenizer = null;
return;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public String next() {
eat();
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasNext() {
eat();
return (tokenizer != null && tokenizer.hasMoreElements());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
public class R035C {
public void debug(Object... objects) { System.err.println(Arrays.deepToString(objects)); }
public static final int INF = 987654321;
public static final long LINF = 987654321987654321L;
public static final double EPS = 1e-9;
Scanner scanner;
PrintWriter out;
int[][] iss;
public R035C() {
try {
this.scanner = new Scanner(new File("input.txt"));
this.out = new PrintWriter("output.txt");
} catch(FileNotFoundException ex) { ex.printStackTrace(); }
}
class Point implements Comparable<Point> {
int x, y, count;
Point(int x, int y) { this.x = x; this.y = y; }
public int hashCode() { return x * 17 + y; }
public boolean equals(Object o) {
if(!(o instanceof Point)) return false;
Point that = (Point)o;
return this.x == that.x && this.y == that.y;
}
public int compareTo(Point that) { return this.count - that.count; }
public String toString() { return "(" + x + ", " + y + ":" + count + ")"; }
}
int[] dx = new int[] { 0, 0, -1, 1 };
int[] dy= new int[] { -1, 1, 0, 0 };
int n, m;
Queue<Point> q;
Point bfs() {
int max = -INF;
Point p = null;
while(!q.isEmpty()) {
Point cur = q.remove();
if(max < cur.count) { max = cur.count; p = cur; }
for(int i=0; i<dx.length; i++) {
int nx = cur.x + dx[i];
int ny = cur.y + dy[i];
if(nx < 0 || nx >= n) { continue; }
if(ny < 0 || ny >= m) { continue; }
Point np = new Point(nx, ny);
if(iss[nx][ny] != 0) { continue; }
np.count = cur.count+1;
iss[nx][ny] = np.count;
q.add(np);
}
}
return p;
}
private void solve() {
this.n = scanner.nextInt();
this.m = scanner.nextInt();
this.iss = new int[n][m];
int k = scanner.nextInt();
q = new PriorityQueue<Point>();
for(int i=0; i<k; i++) {
int x = scanner.nextInt() - 1;
int y = scanner.nextInt() - 1;
Point init = new Point(x, y);
init.count = 1;
q.add(init);
iss[x][y] = 1;
}
Point p = bfs();
out.println((p.x+1) + " " + (p.y+1));
}
private void finish() { this.out.close(); }
public static void main(String[] args) {
R035C obj = new R035C();
obj.solve();
obj.finish();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author zodiacLeo
*/
public class Main
{
public static void main(String[] args)
{
InputStream inputStream;
try
{
inputStream = new FileInputStream("input.txt");
} catch (IOException e)
{
throw new RuntimeException(e);
}
OutputStream outputStream;
try
{
outputStream = new FileOutputStream("output.txt");
} catch (IOException e)
{
throw new RuntimeException(e);
}
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC
{
public void solve(int testNumber, FastScanner in, FastPrinter out)
{
int n = in.nextInt();
int m = in.nextInt();
int p = in.nextInt();
int[] x = new int[p];
int[] y = new int[p];
for (int i = 0; i < p; i++)
{
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int X = x[0];
int Y = y[0];
int D = -1;
for (int dx = 1; dx <= n; dx++)
{
int x1 = dx;
int y1 = 1;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int dx = 1; dx <= n; dx++)
{
int x1 = dx;
int y1 = m;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int dy = 1; dy <= m; dy++)
{
int x1 = 1;
int y1 = dy;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int dy = 1; dy <= m; dy++)
{
int x1 = n;
int y1 = dy;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int i = 1; i <= Math.min(m, n); i++)
{
int x1 = i;
int y1 = i;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
for (int i = 1, ii = m; i <= n && ii >= 1; i++, ii--)
{
int x1 = i;
int y1 = ii;
int xx = 0;
int yy = 0;
int minD = Integer.MAX_VALUE;
for (int j = 0; j < p; j++)
{
int d = Math.abs(x1 - x[j]) + Math.abs(y1 - y[j]);
if (d < minD)
{
minD = d;
xx = x1;
yy = y1;
}
}
if (D < minD && minD != 0 && minD != Integer.MAX_VALUE)
{
D = minD;
X = xx;
Y = yy;
}
}
out.println(X + " " + Y);
}
}
static class FastScanner
{
public BufferedReader br;
public StringTokenizer st;
public FastScanner(InputStream is)
{
br = new BufferedReader(new InputStreamReader(is));
}
public FastScanner(File f)
{
try
{
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public String next()
{
while (st == null || !st.hasMoreElements())
{
String s = null;
try
{
s = br.readLine();
} catch (IOException e)
{
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
static class FastPrinter extends PrintWriter
{
public FastPrinter(OutputStream out)
{
super(out);
}
public FastPrinter(Writer out)
{
super(out);
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class P035C {
private class Pair {
private int x;
private int y;
private Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int hashCode() {
return 37 * x + y;
}
public boolean equals(Object other) {
if (other instanceof Pair) {
Pair otherPair = (Pair)other;
return x == otherPair.x && y == otherPair.y;
}
return false;
}
}
private boolean[][] visited;
private final int N;
private final int M;
private final int k;
private ArrayList<Pair> fires = new ArrayList<Pair>();
private ArrayList<Pair> neighbors = new ArrayList<Pair>();
public P035C() throws IOException {
Scanner sc = new Scanner(new File("input.txt"));
N = sc.nextInt();
M = sc.nextInt();
visited = new boolean[N][M];
k = sc.nextInt();
for (int i = 0; i < k; i++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
fires.add(new Pair(x, y));
}
bfs();
}
private void bfs() throws IOException{
java.util.Queue<Pair> queue = new ArrayDeque<Pair>();
for (Pair p : fires) {
queue.add(p);
visited[p.x][p.y] = true;
}
Pair last = fires.get(0);
while (!queue.isEmpty()) {
Pair p = last = queue.poll();
for (Pair pn : getNeighbors(p)) {
if (!visited[pn.x][pn.y]) {
queue.add(pn);
visited[pn.x][pn.y] = true;
}
}
}
PrintWriter output = new PrintWriter(new FileWriter(new File("output.txt")));
output.printf("%d %d\n", last.x + 1, last.y + 1);
output.close();
}
private Collection<Pair> getNeighbors(Pair p) {
neighbors.clear();
if (p.x > 0) neighbors.add(new Pair(p.x-1, p.y));
if (p.x < N-1) neighbors.add(new Pair(p.x+1, p.y));
if (p.y > 0) neighbors.add(new Pair(p.x, p.y-1));
if (p.y < M-1) neighbors.add(new Pair(p.x, p.y+1));
return neighbors;
}
public static void main(String[] args) throws IOException {
P035C solution = new P035C();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Problem implements Runnable {
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private BufferedReader in;
private PrintWriter out;
private StringTokenizer tok = new StringTokenizer("");
private void init() throws FileNotFoundException {
Locale.setDefault(Locale.US);
String fileName = "";
/* if (ONLINE_JUDGE && fileName.isEmpty()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
if (fileName.isEmpty()) {*/
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
/* } else {
in = new BufferedReader(new FileReader(fileName + ".in"));
out = new PrintWriter(fileName + ".out");
/* }
}*/
}
String readString() {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() {
return Integer.parseInt(readString());
}
long readLong() {
return Long.parseLong(readString());
}
double readDouble() {
return Double.parseDouble(readString());
}
int[] readIntArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = readInt();
}
return a;
}
public static void main(String[] args) {
//new Thread(null, new _Solution(), "", 128 * (1L << 20)).start();
new Problem().run();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
@Override
public void run() {
try {
timeBegin = System.currentTimeMillis();
init();
solve();
out.close();
time();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
int[][] dist;
int n, m;
private void solve() throws IOException {
n = readInt();
m = readInt();
int k=readInt();
dist = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
dist[i][j] = -1;
for (int i = 0; i < k; i++) {
dist[readInt()-1][readInt()-1]=0;
}
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
if (dist[i][j]==0)
bfs(i, j);
int max=0,X=0,Y=0;
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
if (dist[i][j]>=max){
max=dist[i][j];
X=i+1; Y=j+1;
}
out.println(X+" "+Y);
}
public void bfs(int x, int y) {
int[] dx = {0, 1, 0, -1};
int[] dy = {1, 0, -1, 0};
dist[x][y] = 0;
ArrayDeque<P> q = new ArrayDeque<>();
q.add(new P(x, y));
while (!q.isEmpty()) {
P v = q.poll();
for (int i = 0; i < 4; i++) {
int nx = v.x + dx[i];
int ny = v.y + dy[i];
if (inside(nx, ny) && (dist[nx][ny] == -1 || (dist[nx][ny] > dist[v.x][v.y] + 1&&dist[nx][ny]!=0))) {
q.add(new P(nx, ny));
dist[nx][ny] = dist[v.x][v.y] + 1;
}
}
}
}
public boolean inside(int x, int y) {
if (x < n && y < m && x >= 0 && y >= 0) {
return true;
}
return false;
}
}
class P {
int x, y;
public P(int x, int y) {
this.x = x;
this.y = y;
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import javafx.util.Pair;
public class FireAgain {
static Queue q=new LinkedList<>();
static boolean[][] fired;
static Pair index = null;
public static void main(String[] args) throws IOException {
// BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in=new BufferedReader(new FileReader("input.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
StringTokenizer s = new StringTokenizer(in.readLine());
int n=Integer.parseInt(s.nextToken());
int m=Integer.parseInt(s.nextToken());
fired=new boolean[n][m];
Pair result=null;
s = new StringTokenizer(in.readLine());
int firenum=Integer.parseInt(s.nextToken());
s = new StringTokenizer(in.readLine());
int i;
ArrayList<Integer> tree=new ArrayList<>();
for(i=0;i<firenum*2;i++){
tree.add(Integer.parseInt(s.nextToken())-1);
}
for(i=0;i<2*firenum-1;i+=2){
fired[tree.get(i)][tree.get(i+1)]=true;
q.add(new Pair(tree.get(i),tree.get(i+1)));
}
index=(Pair) q.peek();
result=bfs((int)index.getKey(),(int)index.getValue(),n,m);
int x1=(int)result.getKey()+1;
int x2=(int)result.getValue()+1;
String str = x1 + " " + x2;
writer.write(str);
writer.close();
}
public static Pair bfs(int x,int y,int xmax,int ymax){
fired[x][y]=true;
while(!q.isEmpty()){
index=(Pair) q.poll();
int i=(int) index.getKey();
int j=(int) index.getValue();
if(i-1>=0){
if(!fired[i-1][j]){
fired[i-1][j]=true;
q.add(new Pair((i-1),j));
}
}if(j-1>=0){
if(!fired[i][j-1]){
fired[i][j-1]=true;
q.add(new Pair(i,(j-1)));
}
} if(i+1<xmax){
if(!fired[i+1][j]){
fired[i+1][j]=true;
q.add(new Pair(i+1,j));
}
} if(j+1<ymax){
if(!fired[i][j+1]){
fired[i][j+1]=true;
q.add(new Pair(i,j+1));
}
}
}
return index;
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class C {
void run() throws IOException {
int n = ni(), m = ni(), k = ni(), q = n * m, h = 0, t = 0, inf = 123456;
int[] x = new int[q], y = new int[q];
int[][] d = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
d[i][j] = inf;
for (int i = 0; i < k; i++) {
int u = ni() - 1, v = ni() - 1;
d[u][v] = 0;
x[t] = u;
y[t] = v;
t++;
}
if (k < q)
while (t != h) {
int u = x[h], v = y[h];
int l = d[u][v] + 1;
h++;
if (u > 0 && d[u - 1][v] > l) {
d[u - 1][v] = l;
x[t] = u - 1;
y[t] = v;
t++;
}
if (u < n - 1 && d[u + 1][v] > l) {
d[u + 1][v] = l;
x[t] = u + 1;
y[t] = v;
t++;
}
if (v > 0 && d[u][v - 1] > l) {
d[u][v - 1] = l;
x[t] = u;
y[t] = v - 1;
t++;
}
if (v < m - 1 && d[u][v + 1] > l) {
d[u][v + 1] = l;
x[t] = u;
y[t] = v + 1;
t++;
}
}
int max = 0, tx = 0, ty = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (d[i][j] > max) {
max = d[i][j];
tx = i;
ty = j;
}
pw.print(1 + tx + " " + (1 + ty));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int ni() throws IOException {
return Integer.parseInt(next());
}
String nl() throws IOException {
return br.readLine();
}
PrintWriter pw;
BufferedReader br;
StringTokenizer st;
public static void main(String[] args) throws IOException {
BufferedReader _br = new BufferedReader(new FileReader(new File("input.txt")));
PrintWriter _pw = new PrintWriter(new FileWriter(new File("output.txt")));
new C(_br, _pw).run();
_br.close();
_pw.close();
}
public C(BufferedReader _br, PrintWriter _pw) {
br = _br;
pw = _pw;
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class FireAgain
{
public static void main(String[] args) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
Scanner sc = new Scanner(in);
int h = sc.nextInt();
int w = sc.nextInt();
int k = sc.nextInt();
int[] xk = new int[k];
int[] yk = new int[k];
for(int i = 0; i < k; i++)
{
int y = sc.nextInt()-1;
int x = sc.nextInt()-1;
xk[i] = x;
yk[i] = y;
}
int best = -1;
int bestx = -1;
int besty = -1;
for(int x = 0; x < w; x++)
{
for(int y = 0; y < h; y++)
{
int cur = 99999;
for(int f = 0; f < k; f++)
{
cur = Math.min(cur, Math.abs(xk[f] - x)+Math.abs(yk[f] - y));
}
if(cur > best)
{
best = cur;
bestx = x;
besty = y;
}
}
}
// System.out.println((besty+1) + " " + (bestx+1));
String s = (besty+1) + " " + (bestx+1);
out.write(s.getBytes());
}finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class C {
Scanner in;
PrintWriter out;
// String INPUT = "3 3 1 1 1";
String INPUT = "";
void solve()
{
int n = ni();
int m = ni();
int k = ni();
int[][] f=new int[k][2];
for(int i=0;i<k;i++) {
f[i][0]=ni()-1;
f[i][1]=ni()-1;
}
int mx=-1;
int resx=0;
int resy=0;
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
int min=Integer.MAX_VALUE;
for(int l=0;l<k;l++) {
min=Math.min(min, Math.abs(f[l][0]-i)+Math.abs(f[l][1]-j));
}
if(min>mx) {
mx=min;
resx=i;
resy=j;
}
}
}
out.println((resx+1)+" "+(resy+1));
}
void run() throws Exception
{
in = INPUT.isEmpty() ? new Scanner(new File("input.txt")) : new Scanner(INPUT);
out = INPUT.isEmpty() ? new PrintWriter("output.txt") : new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception
{
new C().run();
}
int ni() { return Integer.parseInt(in.next()); }
void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); }
static String join(int[] a, int d){StringBuilder sb = new StringBuilder();for(int v : a){sb.append(v + d + " ");}return sb.toString();}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.StringTokenizer;
public class P {
static int N, M, K;
static int dx[] = { 0, 0, 1, -1, 1, 1, -1, -1 };
static int dy[] = { 1, -1, 0, 0, 1, -1, 1, -1 };
static Pair[] b;
static boolean isValid(int x, int y) {
return x >= 0 && y >= 0 && x < N && y < M;
}
static class Pair {
int x, y;
Pair(int i, int j) {
x = i;
y = j;
}
}
static Pair bfs() {
Queue<Pair> q = new LinkedList<Pair>();
int[][] dist = new int[N][M];
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
dist[i][j] = -1;
for (int i = 0; i < K; i++) {
dist[b[i].x][b[i].y] = 0;
q.add(b[i]);
}
while (!q.isEmpty()) {
Pair cur = q.remove();
for (int d = 0; d < 4; d++) {
int X = cur.x + dx[d];
int Y = cur.y + dy[d];
if (isValid(X, Y) && dist[X][Y] == -1) {
dist[X][Y] = dist[cur.x][cur.y] + 1;
Pair P = new Pair(X, Y);
q.add(P);
}
}
}
int max = -1;
Pair MX = null;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++) {
if (dist[i][j] > max) {
max = dist[i][j];
MX = new Pair(i + 1, j + 1);
}
}
return MX;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner("input.txt");
PrintWriter out = new PrintWriter("output.txt");
// Scanner sc = new Scanner(System.in);
// PrintWriter out = new PrintWriter(System.out);
N = sc.nextInt();
M = sc.nextInt();
K = sc.nextInt();
b = new Pair[K];
for (int i = 0; i < K; i++)
b[i] = new Pair(sc.nextInt() - 1, sc.nextInt() - 1);
Pair last = bfs();
out.println((last.x) + " " + (last.y));
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String f) throws FileNotFoundException {
br = new BufferedReader(new FileReader(f));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntArray1(int n) throws IOException {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++)
a[i] = nextInt();
return a;
}
public int[] nextIntArraySorted(int n) throws IOException {
int[] a = nextIntArray(n);
Random r = new Random();
for (int i = 0; i < n; i++) {
int j = i + r.nextInt(n - i);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
Arrays.sort(a);
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public long[] nextLongArray1(int n) throws IOException {
long[] a = new long[n + 1];
for (int i = 1; i <= n; i++)
a[i] = nextLong();
return a;
}
public long[] nextLongArraySorted(int n) throws IOException {
long[] a = nextLongArray(n);
Random r = new Random();
for (int i = 0; i < n; i++) {
int j = i + r.nextInt(n - i);
long t = a[i];
a[i] = a[j];
a[j] = t;
}
Arrays.sort(a);
return a;
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.util.NoSuchElementException;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Alex
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int maxdist = -1, maxrow = -1, maxcol = -1;
int rows = in.ri(), cols = in.ri();
int k = in.ri();
IntPair[] points = new IntPair[k];
for(int i = 0; i < k; i++) points[i] = new IntPair(in.ri(), in.ri());
for(int row = 1; row <= rows; row++) {
for(int col = 1; col <= cols; col++) {
int mindist = Integer.MAX_VALUE;
for(int i = 0; i < k; i++)
mindist = Math.min(mindist, Math.abs(row - points[i].first) + Math.abs(col - points[i].second));
if (mindist > maxdist){
maxdist = mindist;
maxrow = row;
maxcol = col;
}
}
}
out.printLine(maxrow, maxcol);
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ri(){
return readInt();
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class IntPair implements Comparable<IntPair> {
public int first, second;
public IntPair(int first, int second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IntPair intPair = (IntPair) o;
return first == intPair.first && second == intPair.second;
}
public int hashCode() {
int result = first;
result = 31 * result + second;
return result;
}
public int compareTo(IntPair o) {
if (first < o.first)
return -1;
if (first > o.first)
return 1;
if (second < o.second)
return -1;
if (second > o.second)
return 1;
return 0;
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Solution {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int[][] or;
int n;
int m;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
int k = in.nextInt();
ArrayList<Point> arr1 = new ArrayList<>();
ArrayList<Point> arr2 = new ArrayList<>();
for (int i = 0; i < k; i++) {
arr1.add(new Point(in.nextInt(), in.nextInt()));
}
or = new int[n + 1][m + 1];
for (int i = 0; i < k; i++) {
or[arr1.get(i).x][arr1.get(i).y] = -1;
}
Point lastValue = arr1.get(0);
while (arr1.size() > 0 || arr2.size() > 0) {
for (Point p : arr1) {
if (valid(new Point(p.x - 1, p.y))) {
arr2.add(new Point(p.x - 1, p.y));
}
if (valid(new Point(p.x + 1, p.y))) {
arr2.add(new Point(p.x + 1, p.y));
}
if (valid(new Point(p.x, p.y - 1))) {
arr2.add(new Point(p.x, p.y - 1));
}
if (valid(new Point(p.x, p.y + 1))) {
arr2.add(new Point(p.x, p.y + 1));
}
}
arr1.clear();
if (arr2.size() > 0) {
lastValue = arr2.get(0);
}
for (Point p : arr2) {
if (valid(new Point(p.x - 1, p.y))) {
arr1.add(new Point(p.x - 1, p.y));
}
if (valid(new Point(p.x + 1, p.y))) {
arr1.add(new Point(p.x + 1, p.y));
}
if (valid(new Point(p.x, p.y - 1))) {
arr1.add(new Point(p.x, p.y - 1));
}
if (valid(new Point(p.x, p.y + 1))) {
arr1.add(new Point(p.x, p.y + 1));
}
}
arr2.clear();
if (arr1.size() > 0) {
lastValue = arr1.get(0);
}
}
out.println(lastValue.x + " " + lastValue.y);
}
boolean valid(Point p) {
if ((p.x < 1 || p.x > n) ||
(p.y < 1 || p.y > m) ||
or[p.x][p.y] == -1) {
return false;
}
or[p.x][p.y] = -1;
return true;
}
class Point {
int x;
int y;
public Point(int a, int b) {
x = a;
y = b;
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Solution35C {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException{
if (ONLINE_JUDGE){
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException{
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException{
return Integer.parseInt(readString());
}
long readLong() throws IOException{
return Long.parseLong(readString());
}
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
public static void main(String[] args){
new Solution35C().run();
}
public void run(){
try{
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = "+(t2-t1));
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
static class Utils {
private Utils() {}
public static void mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int leftIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (leftIndex < rightIndex) {
if (rightIndex - leftIndex <= MAGIC_VALUE) {
insertionSort(a, leftIndex, rightIndex);
} else {
int middleIndex = (leftIndex + rightIndex) / 2;
mergeSort(a, leftIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, leftIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int leftIndex, int middleIndex, int rightIndex) {
int length1 = middleIndex - leftIndex + 1;
int length2 = rightIndex - middleIndex;
int[] leftArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, leftIndex, leftArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = leftIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = leftArray[i++];
} else {
a[k] = leftArray[i] <= rightArray[j] ? leftArray[i++] : rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int leftIndex, int rightIndex) {
for (int i = leftIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= leftIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
}
void solve() throws IOException{
int n = readInt();
int m = readInt();
int k = readInt();
Point[] focuses = new Point[k];
for(int i = 0; i < k; i++){
int a = readInt() - 1;
int b = readInt() - 1;
focuses[i] = new Point(a,b);
}
int maxI = 0, maxJ = 0;
int max = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++){
int curMin = 1000000;
for(int r = 0; r < k; r++)
if(abs(focuses[r].x - i) + abs(focuses[r].y - j) < curMin){
curMin = abs(focuses[r].x - i) + abs(focuses[r].y - j);
if(curMin < max) break;
}
if(curMin > max){
max = curMin;
maxI = i;
maxJ = j;
}
}
maxI++;
maxJ++;
out.println(maxI + " " + maxJ);
}
static double distance(long x1, long y1, long x2, long y2){
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
static long gcd(long a, long b){
while(a != b){
if(a < b) a -=b;
else b -= a;
}
return a;
}
static long lcm(long a, long b){
return a * b /gcd(a, b);
}
} | cubic | 35_C. Fire Again | CODEFORCES |
//package C;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Fire_Again {
static int N;
static int M;
static int K;
private class Pos {
public int r;
public int c;
int last;
public Pos(int r,int c, int last) {
this.r = r;
this.c = c;
this.last = last;
}
}
static ArrayList<Pos> pos = new ArrayList<>();
static boolean[][] used;// = new boolean[2001][2001];
static int[] rows = {-1,1,0,0};
static int[] cols = {0,0,-1,1};
int LAST = 0;
int lastRow = 1;
int lastCol = 1;
public static void main(String[] args) throws IOException {
Fire_Again fire_again = new Fire_Again();
BufferedReader bufferedReader =
new BufferedReader(new FileReader("input.txt"));
String[] nm = bufferedReader.readLine().split(" ");
N = Integer.parseInt(nm[0]) + 1;
M = Integer.parseInt(nm[1]) + 1;
K = Integer.parseInt(bufferedReader.readLine());
used = new boolean[N][M];
String[] rc = bufferedReader.readLine().split(" ");
for(int k = 0;k < rc.length;k+=2) {
int r = Integer.parseInt(rc[k]);
int c = Integer.parseInt(rc[k+1]);
pos.add(fire_again.new Pos(r,c,0));
}
fire_again.bfs();
PrintStream ps = new PrintStream("output.txt");
ps.printf("%d %d\n",fire_again.lastRow,fire_again.lastCol);
ps.flush();
ps.close();
}
Queue<Pos> queue = new LinkedList<>();
private void bfs() {
queue.addAll(pos);
for(Pos p : pos) {
used[p.r][p.c] = true;
// System.out.println("r = "+(p.r) + " c = " + (p.c));
}
while(!queue.isEmpty()) {
Pos p = queue.poll();
if(p.last > LAST) {
LAST = p.last;
lastRow = p.r;
lastCol = p.c;
}
for(int i = 0;i < rows.length;i++) {
int currR = p.r;
int currC = p.c;
if(currR + rows[i] >= 1 && currR + rows[i] < N &&
currC + cols[i] >= 1 && currC + cols[i] < M &&
!used[currR + rows[i] ] [currC + cols[i] ] ) {
// System.out.println("r = "+(currR+rows[i]) + " c = " + (currC+cols[i]));
queue.add(new Pos(currR+rows[i],currC+cols[i],p.last+1));
used[currR + rows[i] ] [currC + cols[i] ] = true;
}
}
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.util.LinkedList;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Collection;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Queue;
import java.io.IOException;
import java.io.FileOutputStream;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
Queue<Point> points = new LinkedList<Point>();
int[][] burnTime = new int[n][m];
boolean[][] visited = new boolean[n][m];
for (int i = 0; i < k; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
visited[x][y] = true;
burnTime[x][y] = 0;
points.add(new Point(x, y));
}
int[] dx = new int[]{-1, 0, 0, 1};
int[] dy = new int[]{0, -1, 1, 0};
while (points.size() != 0) {
Point cur = points.poll();
int x = cur.x;
int y = cur.y;
for (int i = 0; i < dx.length; i++) {
int nextX = x + dx[i];
int nextY = y + dy[i];
if (nextX >= 0 && nextX < n && nextY >= 0 && nextY < m && (burnTime[x][y] + 1 < burnTime[nextX][nextY] || !visited[nextX][nextY])) {
points.add(new Point(nextX, nextY));
visited[nextX][nextY] = true;
burnTime[nextX][nextY] = burnTime[x][y] + 1;
}
}
}
int x, y;
x = y = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (burnTime[i][j] > burnTime[x][y]) {
x = i;
y = j;
}
}
}
out.printf("%d %d", x + 1, y + 1);
}
}
class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class C {
private static boolean marked[][] ;
public static void main(String[] args) throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// InputStream inputStream = System.in;
// OutputStream outputStream = System.out;
// InputReader s = new InputReader(inputStream);
// PrintWriter out = new PrintWriter(outputStream);
// input.txt / output.txt
File file = new File("input.txt") ;
Scanner s = new Scanner(file) ;
int n = s.nextInt();
int m = s.nextInt();
marked = new boolean [n + 1 ][m + 1] ;
int k = s.nextInt();
Queue<Point> queue = new LinkedList<Point>();
for(int i =0 ; i < k ; ++i){
int tempX = s.nextInt() ;
int tempY = s.nextInt() ;
marked[tempX][tempY] = true ;
queue.add(new Point(tempX , tempY));
}
Point c = null ;
while(!queue.isEmpty()){
c = queue.poll() ;
if(c.x>1 && !marked[c.x-1][c.y]){
marked[c.x -1 ][c.y] = true ;
queue.add(new Point(c.x-1,c.y));
}
if(c.y>1 && !marked[c.x][c.y-1]){
marked[c.x][c.y-1] = true ;
queue.add(new Point(c.x,c.y-1));
}
if(c.x < n && !marked[c.x+1][c.y]){
marked[c.x + 1 ][c.y] = true ;
queue.add(new Point(c.x + 1,c.y));
}
if(c.y < m && !marked[c.x][c.y+1]){
marked[c.x][c.y+1] = true ;
queue.add(new Point(c.x,c.y+1));
}
}
PrintWriter out = new PrintWriter(new File("output.txt"));
out.println(c.x+" "+c.y);
out.close();
}
static class Point {
int x ;
int y ;
public Point(int x ,int y ){
this.x = x ;
this.y = y ;
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws Exception {
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
int r = readInt();
int c = readInt();
int n = readInt();
int[][] dist = new int[r][c];
for(int i = 0; i < r; i++) {
Arrays.fill(dist[i], 1 << 25);
}
LinkedList<State> q = new LinkedList<State>();
while(n-- > 0) {
q.add(new State(readInt()-1, readInt()-1));
dist[q.peekLast().x][q.peekLast().y] = 0;
}
int[] dx = new int[]{-1,1,0,0};
int[] dy = new int[]{0,0,-1,1};
State ret = q.peekLast();
while(!q.isEmpty()) {
State curr = q.removeFirst();
ret = curr;
for(int k = 0; k < dx.length; k++) {
int nx = curr.x + dx[k];
int ny = curr.y + dy[k];
if(nx >= 0 && nx < r && ny >= 0 && ny < c && dist[nx][ny] > 1 + dist[curr.x][curr.y]) {
dist[nx][ny] = 1 + dist[curr.x][curr.y];
q.add(new State(nx, ny));
}
}
}
pw.println(ret.x+1 + " " + (ret.y+1));
}
exitImmediately();
}
static class State {
public int x,y;
public State(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextLine() throws IOException {
if(!br.ready()) {
exitImmediately();
}
st = null;
return br.readLine();
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws IOException {
File f = new File("input.txt");
Scanner sc = new Scanner(f);
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")));
int n = sc.nextInt();
int m = sc.nextInt();
boolean[][] grid = new boolean[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++)
grid[i][j] = false;
Queue<Pair> q = new LinkedList<>();
int cnt = sc.nextInt();
for (int i = 0; i < cnt; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
x--;
y--;
grid[x][y] = true;
q.add(new Pair(x, y));
}
Pair last = new Pair(-1, -1);
while (!q.isEmpty()) {
Pair current = q.poll();
last = current;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i != 0 && j != 0) continue;
if (inside(current.x + i, current.y + j, n, m) &&
!grid[current.x + i][current.y + j]) {
grid[current.x + i][current.y + j] = true;
q.add(new Pair(current.x + i, current.y + j));
//bw.append((current.x + i) + " " + (current.y + j) + "\n");
}
}
}
}
bw.append((last.x + 1) + " " + (last.y + 1) + "\n");
bw.flush();
bw.close();
sc.close();
}
static class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
private static boolean inside(int a, int b, int n, int m) {
return (a >= 0 && a < n && b >= 0 && b < m);
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.util.*;
import java.io.*;
public class C {
private static int[] dx = {1, -1, 0, 0};
private static int[] dy = {0, 0, -1, 1};
public static void main(String[] args) throws Exception{
Thread t = new Thread(null, null, "~", Runtime.getRuntime().maxMemory()){
@Override
public void run(){
try {
solve();
} catch(Exception e) {
System.err.println("ERROR");
}
}
};
t.start();
t.join();
}
public static void solve() throws Exception {
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int n = in.nextInt();
int m = in.nextInt();
int[][] time = new int[n][m];
for(int i = 0; i < n; ++i) {
Arrays.fill(time[i], Integer.MAX_VALUE);
}
int qq = in.nextInt();
int[] xs = new int[qq];
int[] ys = new int[qq];
for(int i = 0; i < qq; ++i){
xs[i] = in.nextInt() - 1;
ys[i] = in.nextInt() - 1;
}
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
for(int k = 0; k < qq; ++k) {
int dist = Math.abs(i - xs[k]) + Math.abs(j - ys[k]);
time[i][j] = Math.min(time[i][j], dist);
}
}
}
int max = -1;
int x = -1;
int y = -1;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) if(max < time[i][j]) {
max = time[i][j];
x = i + 1;
y = j + 1;
}
}
out.println(x + " " + y);
out.flush();
out.close();
}
private static class Pair {
int f, s;
int time;
public Pair(int f, int s) {
this.f = f;
this.s = s;
}
public Pair(int f, int s, int time) {
this(f, s);
this.time = time;
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) throws Exception {
File in = new File("input.txt"), out = new File("output.txt");
Scanner s;
PrintWriter pw;
if (in.exists()) {
s = new Scanner(in);
pw = new PrintWriter(out);
} else {
s = new Scanner(System.in);
pw = new PrintWriter(System.out);
}
int n = s.nextInt(), m = s.nextInt();
int k = s.nextInt();
List<int[]> list = new ArrayList<int[]>();
for (int t = 0; t < k; ++t) {
list.add(new int[] { s.nextInt() - 1, s.nextInt() - 1 });
}
int max = 0, mi = 1, mj = 1;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int min = Integer.MAX_VALUE;
for (int[] p : list) {
min = Math.min(min, Math.abs(i - p[0]) + Math.abs(j - p[1]));
}
if (min > max) {
max = Math.max(max, min);
mi = i + 1;
mj = j + 1;
}
}
}
pw.println(mi + " " + mj);
pw.close();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int[] di = {-1,0,1,0};
static int[] dj = {0,1,0,-1};
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner("input.txt");
PrintWriter out = new PrintWriter("output.txt");
Queue<Pair> q = new LinkedList<Pair>();
int n = sc.nextInt(),m = sc.nextInt() , k = sc.nextInt();
boolean [][] vis = new boolean[n][m];
while(k-->0)
q.add(new Pair(sc.nextInt()-1,sc.nextInt()-1));
int ansX = 1 , ansY = 1;
while(!q.isEmpty())
{
Pair cur = q.poll();
if(vis[cur.i][cur.j])continue;
ansX = cur.i ; ansY = cur.j;
vis[cur.i][cur.j] = true;
for (int i = 0; i < di.length; i++) {
int ni = cur.i + di[i] , nj = cur.j + dj[i];
if(ni>=0 && ni<n && nj>=0 && nj<m && !vis[ni][nj])
q.add(new Pair(ni,nj));
}
}
out.append(++ansX+" "+ ++ansY);
out.flush();
}
static class Pair
{
int i,j;
public Pair(int a,int b) {
i = a; j = b;
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(s));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public String nextLine() throws IOException {return br.readLine();}
public long nextLong() throws IOException {return Long.parseLong(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public boolean ready() throws IOException {return br.ready();}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.util.*;
import java.math.*;
import java.io.*;
public class Main
{
public static void main(String args[]) throws IOException
{
Scanner c = new Scanner(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int N=c.nextInt();
int M=c.nextInt();
int A[][]=new int[N][M];
for(int i=0;i<N;i++)
Arrays.fill(A[i],Integer.MAX_VALUE/100);
int K=c.nextInt();
for(int i=0;i<K;i++)
{
int x=c.nextInt()-1;
int y=c.nextInt()-1;
for(int i1=0;i1<N;i1++)
{
for(int j1=0;j1<M;j1++)
A[i1][j1]=Math.min(A[i1][j1],Math.abs(i1-x)+Math.abs(j1-y));
}
}
int maxi=0;
int maxj=0;
for(int i=0;i<N;i++)
{
for(int j=0;j<M;j++)
{
if(A[i][j]>A[maxi][maxj])
{
maxi=i;
maxj=j;
}
}
}
out.println((maxi+1)+" "+(maxj+1));
out.close();
}
}
//must declare new classes here | cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.Point;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class FireAgain {
int k, i, j,n,m,x,y;
void run() {
try {
BufferedReader bfd = new BufferedReader(new FileReader("input.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("output.txt"));
// BufferedReader bfd = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tk = new StringTokenizer(bfd.readLine());
n = Integer.parseInt(tk.nextToken());
m = Integer.parseInt(tk.nextToken());
boolean vis[][] = new boolean[n][m];
k = Integer.parseInt(bfd.readLine());
tk = new StringTokenizer(bfd.readLine());
Queue<Point> q = new LinkedList<Point>();
Point last = new Point(0,0);
while(k-->0){
x = Integer.parseInt(tk.nextToken())-1;
y = Integer.parseInt(tk.nextToken())-1;
q.add(new Point(x,y));
vis[x][y] = true;
}
while(!q.isEmpty()) {
Point frnt = q.poll();
for(i=frnt.x-1;i<=frnt.x+1;++i)
for(j=frnt.y-1;j<=frnt.y+1;++j)
if(val(i,j)&& !vis[i][j]&&(frnt.x==i||frnt.y==j)){
q.add(new Point(i,j));
last = new Point(i,j);
vis[i][j] = true;
}
}
// System.out.println(last.x+1 + " " +(last.y+1));
out.write(last.x+1 + " " +(last.y+1)+"\n");
out.flush();
out.close();
} catch (Exception e) {
}
}
boolean val(int x,int y){
return x>=0&&x<n&&y>=0&&y<m;
}
public static void main(String[] args) {
new FireAgain().run();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Queue;
import java.io.BufferedReader;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Nasko
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
int M = in.nextInt();
int[][] dist = new int[N][M];
for (int[] ini : dist) Arrays.fill(ini, (1 << 30));
int K = in.nextInt();
Queue<Integer> q = new LinkedList<Integer>();
for (int k = 0; k < K; ++k) {
int r = in.nextInt() - 1;
int c = in.nextInt() - 1;
dist[r][c] = 0;
q.offer(r);
q.offer(c);
}
int[] dx = new int[]{1, -1, 0, 0};
int[] dy = new int[]{0, 0, 1, -1};
while (!q.isEmpty()) {
int rr = q.poll();
int cc = q.poll();
for (int a = 0; a < 4; ++a) {
int x = dx[a] + rr;
int y = dy[a] + cc;
if (x >= 0 && x < N && y >= 0 && y < M) {
if (dist[x][y] > dist[rr][cc] + 1) {
dist[x][y] = dist[rr][cc] + 1;
q.offer(x);
q.offer(y);
}
}
}
}
int max = 0;
for (int i = 0; i < N; ++i)
for (int j = 0; j < M; ++j)
max = Math.max(max, dist[i][j]);
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
if (max == dist[i][j]) {
out.println((i + 1) + " " + (j + 1));
return;
}
}
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.awt.Point;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class BetaRound35_C implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws IOException {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
@Override
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
public static void main(String[] args) {
new Thread(new BetaRound35_C()).start();
}
void solve() throws IOException {
int n = readInt();
int m = readInt();
int k = readInt();
Queue<Point> q = new ArrayDeque<Point>();
boolean[][] visited = new boolean[n + 2][m + 2];
for (int j = 0; j < m + 2; j++) {
visited[0][j] = true;
visited[n + 1][j] = true;
}
for (int i = 0; i < n + 2; i++) {
visited[i][0] = true;
visited[i][m + 1] = true;
}
for (int i = 0; i < k; i++) {
int x = readInt();
int y = readInt();
q.add(new Point(x, y));
visited[x][y] = true;
}
Point p = null;
while (!q.isEmpty()) {
p = q.poll();
int x = p.x, y = p.y;
if (!visited[x + 1][y]) {
q.add(new Point(x + 1, y));
visited[x + 1][y] = true;
}
if (!visited[x - 1][y]) {
q.add(new Point(x - 1, y));
visited[x - 1][y] = true;
}
if (!visited[x][y + 1]) {
q.add(new Point(x, y + 1));
visited[x][y + 1] = true;
}
if (!visited[x][y - 1]) {
q.add(new Point(x, y - 1));
visited[x][y - 1] = true;
}
}
out.print(p.x + " " + p.y);
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
/**
* Created by tmdautov on 07.02.18.
*/
public class ArFireAgain {
int n, m, k;
int dx[] = { 0, 0, 1, -1, 1, 1, -1, -1 };
int dy[] = { 1, -1, 0, 0, 1, -1, 1, -1 };
int[][] dist;
ArrayList<Pair> arr;
// res -> get coordinates of most remote tree
Scanner sc;
PrintWriter out;
public void solve() {
try {
sc = new Scanner(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
arr = new ArrayList<Pair>();
for (int i=0; i<k; i++) {
int x = sc.nextInt()-1;
int y = sc.nextInt()-1;
Pair p = new Pair(x, y);
arr.add(p);
}
//out.println("helll");
Pair last = bfs();
out.println(last.x + " " + last.y);
out.flush();
out.close();
}
boolean inBoard(int x, int y) {
return x >= n || x < 0 || y >= m || y < 0;
}
boolean isValid(int x, int y) {
return x >= 0 && y >= 0 && x < n && y < m;
}
private Pair bfs() {
// 1. create objects
Queue<Pair> q = new LinkedList<Pair>();
dist = new int[n][m];
// 2. fill dist array with -1
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
dist[i][j] = -1;
}
}
// 3. fill queue with fired k-trees
for (int i=0; i<k; i++) {
dist[arr.get(i).x][arr.get(i).y] = 0; // dist to fired trees is 0
q.add(arr.get(i));
}
// 4. run bfs
while(!q.isEmpty()) {
Pair cur = q.remove();
for (int d=0; d<4; d++) {
int X = cur.x + dx[d];
int Y = cur.y + dy[d];
if (isValid(X, Y) && dist[X][Y] == -1) {
dist[X][Y] = dist[cur.x][cur.y] + 1;
Pair p = new Pair(X, Y);
q.add(p);
}
}
//System.out.println(cur);
}
// 5. find max pair by dist array
Pair res = null;
int maxx = -1;
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
if (dist[i][j] > maxx) {
maxx = dist[i][j];
res = new Pair(i+1, j+1);
}
}
}
return res;
}
// how to sort array of pairs?
class Pair {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
new ArFireAgain().solve();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import static java.lang.Math.*;
public class Main {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
public static void main(String[] args) {
new Main().run();
// Sworn to fight and die
}
public static void mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int levtIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (levtIndex < rightIndex) {
if (rightIndex - levtIndex <= MAGIC_VALUE) {
insertionSort(a, levtIndex, rightIndex);
} else {
int middleIndex = (levtIndex + rightIndex) / 2;
mergeSort(a, levtIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, levtIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int levtIndex, int middleIndex,
int rightIndex) {
int length1 = middleIndex - levtIndex + 1;
int length2 = rightIndex - middleIndex;
int[] levtArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, levtIndex, levtArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = levtIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = levtArray[i++];
} else {
a[k] = levtArray[i] <= rightArray[j] ? levtArray[i++]
: rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int levtIndex, int rightIndex) {
for (int i = levtIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= levtIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
class LOL implements Comparable<LOL> {
int x;
int y;
public LOL(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(LOL o) {
return (x - o.x); // ---->
//return o.x * o.y - x * y; // <----
}
}
class LOL2 implements Comparable<LOL2> {
int x;
int y;
int z;
public LOL2(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int compareTo(LOL2 o) {
return (z - o.z); // ---->
//return o.x * o.y - x * y; // <----
}
}
class test implements Comparable<test> {
long x;
long y;
public test(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(test o) {
//int compareResult = Long.compare(y, o.y); // ---->
//if (compareResult != 0) {
// return -compareResult;
//}
int compareResult = Long.compare(x, o.x);
if (compareResult != 0) {
return compareResult;
}
return Long.compare(y, o.y);
//return o.x * o.y - x * y; // <----
}
}
class data {
String name;
String city;
data(String name, String city) {
this.city = city;
this.name = name;
}
}
class Point {
double x;
double y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
double distance(Point temp) {
return Math.sqrt((x - temp.x) * (x - temp.x) + (y - temp.y) * (y - temp.y));
}
double sqrDist(Point temp) {
return ((x - temp.x) * (x - temp.x) + (y - temp.y) * (y - temp.y));
}
Point rotate(double alpha) {
return new Point(x * cos(alpha) - y * sin(alpha), x * sin(alpha) + y * cos(alpha));
}
void sum(Point o) {
x += o.x;
y += o.y;
}
void scalarProduct(int alpha) {
x *= alpha;
y *= alpha;
}
}
class Line {
double a;
double b;
double c;
Line(Point A, Point B) {
a = B.y - A.y;
b = A.x - B.x;
c = -A.x * a - A.y * b;
}
Line(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
Point intersection(Line o) {
double det = a * o.b - b * o.a;
double det1 = -c * o.b + b * o.c;
double det2 = -a * o.c + c * o.a;
return new Point(det1 / det, det2 / det);
}
}
/* class Plane {
double a;
double b;
double c;
double d;
Plane (Point fir, Point sec, Point thi) {
double del1 = (sec.y - fir.y) * (thi.z - fir.z) - (thi.y - fir.y) * (sec.z - fir.z);
double del2 = (thi.x - fir.x) * (sec.z - fir.z) - (thi.z - fir.z) * (sec.x - fir.x);
double del3 = (thi.y - fir.y) * (sec.x - fir.x) - (thi.x - fir.x) * (sec.y - fir.y);
a = del1;
b = del2;
c = del3;
d = -fir.x * del1 - fir.y * del2 - fir.z * del3;
}
double distance(Point point) {
return abs(a * point.x + b * point.y + c * point.z + d) / sqrt(a * a + b * b + c * c);
}
} */
class record implements Comparable<record> {
String city;
Long score;
public record(String name, Long score) {
this.city = name;
this.score = score;
}
@Override
public int compareTo(record o) {
if (o.city.equals(city)) {
return 0;
}
if (score.equals(o.score)) {
return 1;
}
if (score > o.score) {
return 666;
} else {
return -666;
}
//return Long.compare(score, o.score);
}
}
public long gcd(long a, long b) {
if (a == 0 || b == 0) return max(a, b);
if (a % b == 0)
return b;
else
return gcd(b, a % b);
}
boolean prime(long n) {
if (n == 1) return false;
for (int i = 2; i <= sqrt(n); i++)
if (n % i == 0)
return false;
return true;
}
public int sum(long n) {
int s = 0;
while (n > 0) {
s += (n % 10);
n /= 10;
}
return s;
}
/* public void simulation(int k) {
long ans = 0;
int start = 1;
for (int i = 0; i < k; i++) {
start *= 10;
}
for (int i = start/10; i < start; i++) {
int locAns = 0;
for (int j = start/10; j < start; j++) {
if (sum(i + j) == sum(i) + sum(j) ) {
ans += 1;
locAns += 1;
} else {
//.println(i + "!!!" + j);
}
}
//out.println(i + " " + locAns);
}
out.println(ans);
}*/
ArrayList<Integer> primes;
boolean[] isPrime;
public void getPrimes (int n) {
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
primes.add(i);
if (1l * i * i <= n) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
}
}
public long binPowMod(long a, long b, long mod) {
if (b == 0) {
return 1 % mod;
}
if (b % 2 != 0) {
return ((a % mod) * (binPowMod(a, b - 1, mod) % mod)) % mod;
} else {
long temp = binPowMod(a, b / 2, mod) % mod;
long ans = (temp * temp) % mod;
return ans;
}
}
int type[];
boolean vis[];
HashMap<Integer, HashSet<Integer>> g;
int componentNum[];
/* void dfs(int u, int numOfComponent) {
vis[u] = true;
componentNum[u] = numOfComponent;
for (Integer v: g.get(u)) {
if (!vis[v]) {
dfs(v, numOfComponent);
}
}
} */
int p[];
int find(int x) {
if (x == p[x]) {
return x;
}
return p[x] = find(p[x]);
}
boolean merge(int x, int y) {
x = find(x);
y = find(y);
if (p[x] == p[y]) {
return false;
}
p[y] = x;
return true;
}
class Trajectory {
double x0;
double y0;
double vx;
double vy;
Trajectory(double vx, double vy, double x0, double y0) {
this.vx = vx;
this.vy = vy;
this.x0 = x0;
this.y0 = y0;
}
double y (double x) {
return y0 + (x - x0) * (vy / vx) - 5 * (x - x0) * (x - x0) / (vx * vx);
}
double der(double x) {
return (vy / vx) - 10 * (x - x0) / (vx * vx);
}
}
int s;
int n;
int m;
boolean isVisited[][];
char[][] maze;
int[] dx = {0, 0, -1, 1};
int[] dy = {1, -1, 0, 0};
void dfs(int x, int y) {
isVisited[x][y] = true;
for (int i = 0; i < 4; i++) {
int currX = x + dx[i];
int currY = y + dy[i];
if (maze[currX][currY] == '.' && !isVisited[currX][currY]) {
dfs(currX, currY);
}
}
}
public void solve() throws IOException {
n = readInt();
m = readInt();
maze = new char[n + 2][m + 2];
for (int i = 0; i < n + 2; i++) {
maze[i][0] = '#';
maze[i][m + 1] = '#';
}
for (int j = 0; j < m + 2; j++) {
maze[0][j] = '#';
maze[n + 1][j] = '#';
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
maze[i][j] = '.';
}
}
int[][] dist = new int[n + 2][m + 2];
for (int i = 0; i < n + 2; i++) {
for (int j = 0; j < m + 2; j++) {
dist[i][j] = Integer.MAX_VALUE;
}
}
ArrayDeque<Integer> xValues = new ArrayDeque<Integer>();
ArrayDeque<Integer> yValues = new ArrayDeque<Integer>();
int k = readInt();
for (int i = 0; i < k; i++) {
int currX = readInt();
int currY = readInt();
xValues.add(currX);
yValues.add(currY);
dist[currX][currY] = 0;
}
while(!xValues.isEmpty()) {
int x = xValues.poll();
int y = yValues.poll();
for (int i = 0; i < 4; i++) {
int currX = x + dx[i];
int currY = y + dy[i];
if (maze[currX][currY] == '.' && dist[currX][currY] > dist[x][y] + 1) {
dist[currX][currY] = dist[x][y] + 1;
xValues.add(currX);
yValues.add(currY);
}
}
}
int maxDist = 0;
int indexX = 0;
int indexY = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (dist[i][j] >= maxDist) {
maxDist = dist[i][j];
indexX = i;
indexY = j;
}
}
}
out.print(indexX + " " + indexY);
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.File;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public String[][] a;
public void run () throws Exception {
Scanner in = new Scanner(new File("input.txt"));
PrintWriter pw = new PrintWriter(new File("output.txt"));
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[] xx = new int[k];
int[] yy = new int[k];
for(int i=0;i<k;i++){
xx[i] = in.nextInt();
yy[i]= in.nextInt();
}
int x=0,y=0,r;
r=-1;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++){
int rr = 1000000;
for(int q=0;q<k;q++)
rr = Math.min(rr, Math.abs(xx[q]-1-i)+Math.abs(yy[q]-1-j));
if(rr>r){
r=rr;
x=i;
y=j;
}
}
pw.print((x+1)+" "+(y+1));
pw.close();
}
public static void main(String[] args) throws Exception {
new Main ().run();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
// :%s/Cbeta35/"name"/
// if (debug)
public class Cbeta35 {
public static void main(String[] args) { new Cbeta35(); }
Scanner in;
PrintWriter out;
int t;
int n, m, k, oo;
int[][] grid;
boolean debug = !true, multi = !true;
Cbeta35() {
if (multi) t = in.nextInt();
do {
if (multi) if (z(t--)) break;
try {
in = new Scanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
}
catch (Exception e) {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
}
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
oo = n + m + 1;
grid = new int[n][m];
for (int i = 0; i < n; i++)
Arrays.fill(grid[i], oo);
for (int i = 0; i < k; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
for (int j = 0; j < n; j++)
for (int kk = 0; kk < m; kk++) {
int dx = j - x < 0 ? x - j : j - x;
int dy = kk - y < 0 ? y - kk : kk - y;
grid[j][kk] = min(grid[j][kk], dx + dy);
}
}
int x = 0, y = 0;
int max = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (max < grid[i][j]) {
max = grid[i][j];
x = i; y = j;
}
out.printf("%d %d%n", x + 1, y + 1);
} while (debug || multi);
out.close();
}
int min(int a, int b) { if (a < b) return a; return b; }
int max(int a, int b) { if (a > b) return a; return b; }
long min(long a, long b) { if (a < b) return a; return b; }
long max(long a, long b) { if (a > b) return a; return b; }
boolean z(int x) { if (x == 0) return true; return false; }
boolean z(long x) { if (x == 0) return true; return false; }
void sort(int[] arr) {
int szArr = arr.length;
Random r = new Random();
for (int i = 0; i < szArr; i++) {
int j = r.nextInt(szArr);
arr[i] = arr[j]^(arr[i]^(arr[j] = arr[i]));
}
Arrays.sort(arr);
}
class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) {}
} return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author madis
*/
public class Pjar {
static int a[][];
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter("output.txt");
int N = in.nextInt();
int M = in.nextInt();
a = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
a[i][j] = Integer.MAX_VALUE;
}
}
int k = in.nextInt();
in.nextLine();
for (int i = 0; i < k; i++) {
int x = in.nextInt();
int y = in.nextInt();
a[x - 1][y - 1] = 1;
burn(x - 1, y - 1);
}
int max = Integer.MIN_VALUE;
int x = 0;
int y = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if(a[i][j]>max){
max = a[i][j];
x = i+1;
y = j+1;
}
}
}
out.printf("%d %d",x,y);
out.close();
in.close();
}
static void burn(int i, int j) {
for(int k = 0;k<a.length;k++){
for(int l=0;l<a[k].length;l++){
if(a[k][l]>Math.abs(k-i) + Math.abs(l-j)){
a[k][l]=Math.abs(k-i) + Math.abs(l-j);
}
}
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
public class R035CRetry {
public void debug(Object... objects) { System.err.println(Arrays.deepToString(objects)); }
public static final int INF = 987654321;
public static final long LINF = 987654321987654321L;
public static final double EPS = 1e-9;
Scanner scanner;
PrintWriter out;
boolean[][] bss;
public R035CRetry() {
try {
this.scanner = new Scanner(new File("input.txt"));
this.out = new PrintWriter("output.txt");
} catch(FileNotFoundException ex) { ex.printStackTrace(); }
}
class Point implements Comparable<Point> {
int x, y, count;
Point(int x, int y) { this.x = x; this.y = y; }
public int hashCode() { return x * 17 + y; }
public boolean equals(Object o) {
if(!(o instanceof Point)) return false;
Point that = (Point)o;
return this.x == that.x && this.y == that.y;
}
public int compareTo(Point that) { return this.count - that.count; }
public String toString() { return "(" + x + ", " + y + ":" + count + ")"; }
}
int[] dx = new int[] { 0, 0, -1, 1 };
int[] dy= new int[] { -1, 1, 0, 0 };
int n, m;
Queue<Point> q;
Point bfs() {
int max = -INF;
Point p = null;
while(!q.isEmpty()) {
Point cur = q.remove();
if(max < cur.count) { max = cur.count; p = cur; }
for(int i=0; i<dx.length; i++) {
int nx = cur.x + dx[i];
int ny = cur.y + dy[i];
if(nx < 0 || nx >= n) { continue; }
if(ny < 0 || ny >= m) { continue; }
Point np = new Point(nx, ny);
if(bss[nx][ny] ) { continue; }
np.count = cur.count+1;
bss[nx][ny] = true;
q.add(np);
}
}
return p;
}
private void solve() {
this.n = scanner.nextInt();
this.m = scanner.nextInt();
this.bss = new boolean[n][m];
int k = scanner.nextInt();
q = new PriorityQueue<Point>();
for(int i=0; i<k; i++) {
int x = scanner.nextInt() - 1;
int y = scanner.nextInt() - 1;
Point init = new Point(x, y);
init.count = 1;
q.add(init);
bss[x][y] = true;
}
Point p = bfs();
out.println((p.x+1) + " " + (p.y+1));
}
private void finish() { this.out.close(); }
public static void main(String[] args) {
R035CRetry obj = new R035CRetry();
obj.solve();
obj.finish();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class cf35c {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int[] dx = {0,0,1,-1};
int[] dy = {1,-1,0,0};
int n = in.nextInt();
int m = in.nextInt();
int[][] seen = new int[n][m];
for(int i=0; i<n; i++)
Arrays.fill(seen[i], -1);
Queue<Integer> q = new LinkedList<Integer>();
int k = in.nextInt();
for(int i=0; i<k; i++) {
int x = in.nextInt()-1;
int y = in.nextInt()-1;
q.add(x);
q.add(y);
q.add(0);
seen[x][y] = 0;
}
while(!q.isEmpty()) {
int x = q.poll();
int y = q.poll();
int t = q.poll();
for(int i=0; i<dx.length; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx < 0 || nx >= n || ny < 0 || ny >= m)
continue;
if(seen[nx][ny] != -1) continue;
seen[nx][ny] = t+1;
q.add(nx);
q.add(ny);
q.add(t+1);
}
}
int best=-1,x=0,y=0;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
if(seen[i][j] > best) {
best = seen[i][j];
x = i+1;
y = j+1;
}
out.println(x + " " +y);
out.close();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class FireAgain {
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream("output.txt"));
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String s[] = r.readLine().split("\\s+");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
int k = Integer.parseInt(r.readLine());
int[][] a = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++)
a[i][j] = Integer.MAX_VALUE;
}
assert k >= 1 && k < n * m;
int max = 0;
StringTokenizer st = new StringTokenizer(r.readLine());
assert st.countTokens() == k;
for(; k > 0; k--) {
int x = Integer.parseInt(st.nextToken()) - 1;
int y = Integer.parseInt(st.nextToken()) - 1;
assert x >= 1 && x <= n && y >= 1 && y <= n;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int d = Math.abs(i - x) + Math.abs(j - y);
if(a[i][j] > d)
a[i][j] = d;
if(k == 1 && a[i][j] > max)
max = a[i][j];
}
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(a[i][j] == max) {
System.out.println((i + 1) + " " + (j + 1));
return;
}
}
}
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class C2 {
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(new File("input.txt"));
PrintWriter pw = new PrintWriter(new File("output.txt"));
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int[]x = new int[k+1], y = new int[k+1];
for (int i = 1; i <= k; i++) {
y[i] = sc.nextInt();
x[i] = sc.nextInt();
}
int max = -1, y0 = 0, x0 = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
int min = n+m+2;
for (int j2 = 1; j2 <= k; j2++) {
min = Math.min(min, Math.abs(i-y[j2])+Math.abs(j-x[j2]));
}
if (min > max) {
max = min;
y0 = i;
x0 = j;
}
}
}
pw.println(y0+" "+x0);
pw.close();
}
}
| cubic | 35_C. Fire Again | CODEFORCES |
import java.util.Scanner;
import java.util.HashSet;
import java.io.PrintWriter;
import java.io.File;
public class FireAgain {
public static void main(String[] args){
File in = new File("input.txt");
File out = new File("output.txt");
Scanner sc;
PrintWriter pw;
try{
sc = new Scanner(in);
pw = new PrintWriter(out);
}catch(Exception e){
sc = new Scanner(System.in);
pw = null;
}
int max_x = sc.nextInt();
int max_y = sc.nextInt();
int start_num = sc.nextInt();
HashSet<int[]> start = new HashSet<int[]>();
for(int i=0; i<start_num; i++){
int[] cell = new int[2];
cell[0] = sc.nextInt();
cell[1] = sc.nextInt();
start.add(cell);
}
int[] result = new int[]{1,1};
int resultLen = 0;
for(int i=1; i<=max_x; i++){
for(int j=1; j<=max_y; j++){
int[] sh = new int[]{1,1};
int shLen = Integer.MAX_VALUE;
for(int[] fired: start){
int len = Math.abs(i - fired[0]) + Math.abs(j - fired[1]);
if(len < shLen){
sh[0] = i;
sh[1] = j;
shLen = len;
}
}
if(shLen > resultLen){
result[0] = sh[0];
result[1] = sh[1];
resultLen = shLen;
}
}
}
pw.print(result[0] + " " + result[1]);
pw.close();
return ;
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.StringTokenizer;
public class CodeForces {
public static void main(String[] args) throws FileNotFoundException {
FastIO io = new FastIO();
int width = io.nextInt();
int height = io.nextInt();
int initials = io.nextInt();
boolean[][] visited = new boolean[width][height];
Queue<Coordinate> q = new ArrayDeque<>();
for (int i = 0; i < initials; i++) {
q.add(new Coordinate(io.nextInt() - 1, io.nextInt() - 1));
}
Coordinate oneOfLast = null;
while (!q.isEmpty()) {
int len = q.size();
for (int times = 0; times < len; times++) {
Coordinate c = q.poll();
if (visited[c.x][c.y]) {
continue;
}
oneOfLast = c;
visited[c.x][c.y] = true;
int[][] deltas = new int[][]{
{-1, 0}, {0, -1}, {1, 0}, {0, 1}
};
for (int[] delta : deltas) {
int ci = c.y + delta[0];
int cj = c.x + delta[1];
if (ci >= 0 && cj >= 0 && ci < height && cj < width) {
q.add(new Coordinate(cj, ci));
}
}
}
}
io.println((oneOfLast.x + 1) + " " + (oneOfLast.y + 1));
io.close();
}
static class Coordinate {
int x;
int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
static class FastIO extends PrintWriter {
BufferedReader br;
StringTokenizer st;
public FastIO() throws FileNotFoundException {
super(new BufferedOutputStream(new FileOutputStream("output.txt")));
br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
} | cubic | 35_C. Fire Again | CODEFORCES |
import java.io.*;
import java.util.*;
public class B {
static int n, t[], g[], MOD = (int) 1e9 + 7;
static int[][][] memo1, memo2[], memo3[];
static int dp1(int idx, int remCnt, int remSum) {
if (idx == n)
return remSum == 0 && remCnt == 0 ? 1 : 0;
if (remCnt < 0 || remSum < 0)
return 0;
if (memo1[idx][remCnt][remSum] != -1)
return memo1[idx][remCnt][remSum];
int ans = dp1(idx + 1, remCnt, remSum);
if (g[idx] == 0) {
ans += dp1(idx + 1, remCnt - 1, remSum - t[idx]);
if (ans >= MOD)
ans -= MOD;
}
return memo1[idx][remCnt][remSum] = ans;
}
static int dp2(int idx, int remCnt1, int remCnt2, int remSum) {
if (idx == n)
return remSum == 0 && remCnt1 == 0 && remCnt2 == 0 ? 1 : 0;
if (remSum < 0 || remCnt1 < 0 || remCnt2 < 0)
return 0;
if (memo2[idx][remCnt1][remCnt2][remSum] != -1)
return memo2[idx][remCnt1][remCnt2][remSum];
int ans = dp2(idx + 1, remCnt1, remCnt2, remSum);
if (g[idx] == 1)
ans += dp2(idx + 1, remCnt1 - 1, remCnt2, remSum - t[idx]);
else if (g[idx] == 2)
ans += dp2(idx + 1, remCnt1, remCnt2 - 1, remSum - t[idx]);
if(ans>=MOD)
ans-=MOD;
return memo2[idx][remCnt1][remCnt2][remSum] = ans;
}
private static int dp3(int cnt0, int cnt1, int cnt2, int last) {
if (cnt0 < 0 || cnt1 < 0 || cnt2 < 0)
return 0;
if (cnt0 + cnt1 + cnt2 == 0)
return 1;
if (memo3[last][cnt0][cnt1][cnt2] != -1)
return memo3[last][cnt0][cnt1][cnt2];
long ans = 0;
if (last != 0)
ans += dp3(cnt0 - 1, cnt1, cnt2, 0);
if (last != 1)
ans += dp3(cnt0, cnt1 - 1, cnt2, 1);
if (last != 2)
ans += dp3(cnt0, cnt1, cnt2 - 1, 2);
return memo3[last][cnt0][cnt1][cnt2] = (int) (ans % MOD);
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
int[] fac = new int[n + 1];
t = new int[n];
g = new int[n];
int[] cnt = new int[3];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = (int) (i * 1L * fac[i - 1] % MOD);
int T = sc.nextInt();
for (int i = 0; i < n; i++) {
t[i] = sc.nextInt();
g[i] = sc.nextInt() - 1;
cnt[g[i]]++;
}
memo1 = new int[n][cnt[0] + 1][T + 1];
memo2 = new int[n][cnt[1] + 1][cnt[2] + 1][T + 1];
memo3 = new int[4][cnt[0] + 1][cnt[1] + 1][cnt[2] + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= cnt[0]; j++)
Arrays.fill(memo1[i][j], -1);
for (int j = 0; j <= cnt[1]; j++)
for (int k = 0; k <= cnt[2]; k++)
Arrays.fill(memo2[i][j][k], -1);
}
for (int i = 0; i < 4; i++)
for (int j = 0; j <= cnt[0]; j++)
for (int k = 0; k <= cnt[1]; k++)
Arrays.fill(memo3[i][j][k], -1);
int ans = 0;
for (int cnt0 = 0; cnt0 <= cnt[0]; cnt0++)
for (int sum0 = 0; sum0 <= T; sum0++)
for (int cnt1 = 0; cnt1 <= cnt[1]; cnt1++)
for (int cnt2 = 0; cnt2 <= cnt[2]; cnt2++) {
long ways = dp1(0, cnt0, sum0) * 1L * dp2(0, cnt1, cnt2, T - sum0) % MOD;
ways = ways * dp3(cnt0, cnt1, cnt2, 3) % MOD;
ways *= fac[cnt0];
ways %= MOD;
ways *= fac[cnt1];
ways %= MOD;
ways *= fac[cnt2];
ways %= MOD;
ans += ways;
if (ans >= MOD)
ans -= MOD;
}
out.println(ans);
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
} | cubic | 1185_G2. Playlist for Polycarp (hard version) | CODEFORCES |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskG2 solver = new TaskG2();
solver.solve(1, in, out);
out.close();
}
static class TaskG2 {
static final int MOD = 1000000000 + 7;
static final int MAXN = 51;
int getWays(int i, int j, int k, int l, int[][][][] ways, boolean[][][][] cached) {
if (i + j + k == 0) return l == -1 ? 1 : 0;
if (l < 0) return 0;
if (cached[i][j][k][l]) return ways[i][j][k][l];
int s = i + j + k;
long value = 0;
if (l == 0 && i != 0) {
for (int x = -1; x < 3; x++)
if (x != l) {
value += getWays(i - 1, j, k, x, ways, cached);
}
}
if (l == 1 && j != 0) {
for (int x = -1; x < 3; x++)
if (x != l) {
value += getWays(i, j - 1, k, x, ways, cached);
}
}
if (l == 2 && k != 0) {
for (int x = -1; x < 3; x++)
if (x != l) {
value += getWays(i, j, k - 1, x, ways, cached);
}
}
ways[i][j][k][l] = (int) (value % MOD);
cached[i][j][k][l] = true;
return ways[i][j][k][l];
}
int totalWays(int i, int j, int k, int[][][][] ways, boolean[][][][] cached, int[] factorial) {
long ret = 0;
for (int l = 0; l < 3; l++) ret += getWays(i, j, k, l, ways, cached);
ret *= factorial[i];
ret %= MOD;
ret *= factorial[j];
ret %= MOD;
ret *= factorial[k];
ret %= MOD;
return (int) ret;
}
int add(int type, int value, int[] sizes, int sum, int[][][][] dp) {
sizes[type]++;
if (type == 0) {
for (int s = sum + value; s >= value; s--) {
for (int i = 1; i <= sizes[0]; i++)
for (int j = 0; j <= sizes[1]; j++)
for (int k = 0; k <= sizes[2]; k++) {
dp[i][j][k][s] += dp[i - 1][j][k][s - value];
if (dp[i][j][k][s] >= MOD)
dp[i][j][k][s] -= MOD;
}
}
}
if (type == 1) {
for (int s = sum + value; s >= value; s--) {
for (int i = 0; i <= sizes[0]; i++)
for (int j = 1; j <= sizes[1]; j++)
for (int k = 0; k <= sizes[2]; k++) {
// System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length);
dp[i][j][k][s] += dp[i][j - 1][k][s - value];
if (dp[i][j][k][s] >= MOD)
dp[i][j][k][s] -= MOD;
}
}
}
if (type == 2) {
for (int s = sum + value; s >= value; s--) {
for (int i = 0; i <= sizes[0]; i++)
for (int j = 0; j <= sizes[1]; j++)
for (int k = 1; k <= sizes[2]; k++) {
// System.out.println(i + " " + j + " " + k + " " + s + " " + dp.length + " " + dp[0].length + " " + dp[0][0].length + " " + dp[0][0][0].length);
dp[i][j][k][s] += dp[i][j][k - 1][s - value];
if (dp[i][j][k][s] >= MOD)
dp[i][j][k][s] -= MOD;
}
}
}
return sum + value;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int[][][][] ways = new int[MAXN][MAXN][MAXN][3];
boolean[][][][] cached = new boolean[MAXN][MAXN][MAXN][3];
// Arrays.fill(ways, -1);
int n = in.nextInt(), T = in.nextInt();
ArrayList<Integer>[] ar = new ArrayList[3];
for (int i = 0; i < 3; i++) ar[i] = new ArrayList<Integer>();
int total_sum = 0;
for (int i = 0; i < n; i++) {
int t = in.nextInt(), g = in.nextInt();
ar[g - 1].add(t);
total_sum += t;
}
if (T > total_sum) {
out.println(0);
return;
}
int min_index = 0, mn = 0;
for (int i = 0; i < 3; i++) {
if (ar[i].size() > mn) {
mn = ar[i].size();
min_index = i;
}
}
int[][][][] dp = new int[ar[(1 + min_index) % 3].size() + 1][ar[(2 + min_index) % 3].size() + 1][1][total_sum + 1];
int[][][][] dp2 = new int[1][1][mn + 1][total_sum + 1];
dp[0][0][0][0] = dp2[0][0][0][0] = 1;
int[] sizes = {0, 0, 0};
int sum = 0;
int[] order = {(min_index + 1) % 3, (min_index + 2) % 3};
int type = 0;
for (int i : order) {
for (int v : ar[i])
sum = add(type, v, sizes, sum, dp);
type++;
}
sum = 0;
sizes[0] = sizes[1] = sizes[2] = 0;
for (int i : ar[min_index])
sum = add(2, i, sizes, sum, dp2);
int[] factorial = new int[MAXN];
factorial[0] = 1;
for (int i = 1; i < MAXN; i++)
factorial[i] = (int) ((factorial[i - 1] * 1L * i) % MOD);
long answer = 0;
for (int i = 0; i < dp.length; i++)
for (int j = 0; j < dp[0].length; j++)
for (int k = 0; k <= mn; k++)
for (int s = 0; s <= T; s++) {
long x = (dp[i][j][0][s] * 1L * totalWays(i, j, k, ways, cached, factorial)) % MOD;
x *= dp2[0][0][k][T - s];
x %= MOD;
answer += x;
}
out.println(answer % MOD);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
writer.print('\n');
}
public void close() {
writer.close();
}
}
}
| cubic | 1185_G2. Playlist for Polycarp (hard version) | CODEFORCES |