318D - Ants - CodeForces Solution


dfs and similar *2000

Please click on ads to support us..

C++ Code:

#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <cmath>
#include <cassert>

using namespace std;


const int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
const int max_side = 100;

int main() {

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n, t; cin >> n >> t;

    vector<vector<int>> g(2 * max_side + 1, vector<int>(2 * max_side + 1, 0));
    int C = 2 * max_side + 1;
    g[max_side][max_side] = n;

    queue<int> q; // pos -> num;
    if(n >= 4) q.push(max_side * C + max_side);
    while(!q.empty()){
        int cx = q.front() / C, cy = q.front() % C;
        q.pop();

        if(g[cx][cy] < 4) continue;

        g[cx][cy] -= 4;
        if(g[cx][cy] >= 4) q.push(cx * C + cy);

        for(int d = 0; d < 4; d ++){
            int nx = cx + dirs[d][0], ny = cy + dirs[d][1], npos = nx * C + ny;
            assert(0 <= nx && nx < g.size() && 0 <= ny && ny < g.size());
            g[nx][ny] += 1;
            if(g[nx][ny] >= 4) q.push(npos);
        }
    }

    while(t --){
        int x, y; cin >> x >> y;
        x += max_side, y += max_side;
        if(x < 0 || x >= g.size() || y < 0 || y >= g.size()) cout << 0 << '\n';
        else cout << g[x][y] << '\n';
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

967. Numbers With Same Consecutive Differences
957. Prison Cells After N Days
946. Validate Stack Sequences
921. Minimum Add to Make Parentheses Valid
881. Boats to Save People
497. Random Point in Non-overlapping Rectangles
528. Random Pick with Weight
470. Implement Rand10() Using Rand7()
866. Prime Palindrome
1516A - Tit for Tat
622. Design Circular Queue
814. Binary Tree Pruning
791. Custom Sort String
787. Cheapest Flights Within K Stops
779. K-th Symbol in Grammar
701. Insert into a Binary Search Tree
429. N-ary Tree Level Order Traversal
739. Daily Temperatures
647. Palindromic Substrings
583. Delete Operation for Two Strings
518. Coin Change 2
516. Longest Palindromic Subsequence
468. Validate IP Address
450. Delete Node in a BST
445. Add Two Numbers II
442. Find All Duplicates in an Array
437. Path Sum III
436. Find Right Interval
435. Non-overlapping Intervals
406. Queue Reconstruction by Height