1 条题解

  • 0
    @ 2025-10-10 19:52:16

    C++ :

    #include <bits/stdc++.h>
    using namespace std;
    
    const int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1};
    
    struct node{
    	int x,y;
    }; 
    
    //标记哪里有奶牛 
    bool f[3000][3000];
    //存储存放奶牛的队列 
    queue<node> q;
    
    //判断如果当前奶牛和另外三个相邻,添加一个新的牛的位置进队列 
    void judge(int x, int y) {
    	//如果这里没有奶牛,退出 
    	if (!f[x][y]) return;
    	 
    	int c = 0;
    	for (int i = 0; i < 4; ++i)
    		c += f[x+dx[i]][y+dy[i]];
    		
    	if (c == 3)
    		for (int i = 0; i < 4; i++) {
    			node n = {x+dx[i],y+dy[i]};
    			if (!f[n.x][n.y])
    				q.push(n);
    		}
    }
    
    int main() {
    	int N;
    	cin >> N;
    	int cnt = 0;//总牛的数量
    	node n;
    	//i:加入进来的牛的数量 
    	for (int i = 1; i <= N; i++) {
    		cin >> n.x>> n.y;
    		//防止越界 
    		n.x += 1000, n.y += 1000;
    		q.push(n);
    
    		while (!q.empty()) {
    			node head = q.front();
    			q.pop();
    			
    			//如果这头牛在棋盘上 
    			if (f[head.x][head.y]) continue;
    			//牛不在棋盘,放棋盘
    			cnt++;
    			f[head.x][head.y] = 1;//牛放入棋盘 
    			judge(head.x,head.y);//判断当前位置
    			//判断四方向 
    			for (int j = 0; j < 4; j++)
    				judge(head.x+dx[j],head.y+dy[j]);
    		}
    		
    		//实际在棋盘上的牛的数量 - 目前位置读入的牛的数量 
    		cout << cnt-i << endl;
    	}
    }
    
    • 1

    信息

    ID
    1070
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者