做题记录 洛谷P2004领地选择

题目链接

这几乎是二维前缀和的模板题。
众所周知,一维前缀和 s u m i sum_i sumi的定义为:对有n个数的数列, s u m i = ∑ k = 1 i a i sum_i=\sum \limits_{k=1}^{i}a_i sumi=k=1iai
那么,二维前缀和 s u m i , j sum_{i,j} sumi,j 自然就是对有n行m列的矩阵, s u m i , j = ∑ i = 1 n ∑ j = 1 m a i , j sum_{i,j}=\sum \limits_{i=1}^{n}\sum \limits_{j=1}^{m}a_{i,j} sumi,j=i=1nj=1mai,j

这就是用了类比的思想。类似的思想有很多应用。比如在高数中,可以由定义在区间上的一元函数的许多定理、公式都可以扩展到定义在平面区域的二元函数。

而题目中是要求固定的CxC方阵,因此只要对二位前缀和做减法即可。注意重复减去的处理。

inline int calc(int i,int j,int c) {
	int l=max(0,j-c),u=max(0,i-c);  //最左边的列和最上边的行 
	return sum[i][j]-sum[u][j]-sum[i][l]+sum[u][l];
}

int main() {
    //省略输入
    for(int i=1; i<=n; i++) {
    	for(int j=1; j<=m; j++) {
    		scanf("%d",&a[i][j]);
    		sum[i][j]=sum[i][j-1]+a[i][j];
		}
		for(int j=1; j<=m; j++)	   sum[i][j]+=sum[i-1][j];
	}
	int maxi=0,maxj=0,maxn=-INF;
	for(int i=c; i<=n; i++) {
		for(int j=c; j<=m; j++) {
			int now=calc(i,j,c);
			if(now>maxn) {
				maxn=now;
				maxi=i;
				maxj=j;
			}
		}
	}
	printf("%d %d",maxi-c+1,maxj-c+1);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您编写这个程序。以下是程序的基本思路: 1. 定义两个拟人角色,每个角色有一个领地和一个小球。 2. 每个角色有两个基本动作:移动和打球。 3. 角色可以移动到自己的领地内,或者向前移动一格。 4. 玩家可以通过键盘输入来控制角色的动作。 5. 如果一个角色将小球打入对方领地,那么这个角色获得一分。 6. 游戏终止条件:一方获得 5 分或者游戏时间到。 下面是程序的核心代码: ```python import random class Player: def __init__(self, name): self.name = name self.score = 0 self.pos = 0 def move(self): choice = input(f"{self.name}, please choose your move (1: stay, 2: move forward): ") if choice == "1": print(f"{self.name} stays in place.") elif choice == "2": self.pos += 1 print(f"{self.name} moves to position {self.pos}.") else: print("Invalid input.") self.move() def hit_ball(self, other): if self.pos == 0: print(f"{self.name} can't hit the ball from their own territory.") else: if random.random() < 0.5: print(f"{self.name} hits the ball towards {other.name}'s territory!") if self.pos > other.pos: print(f"{self.name} scores a point!") self.score += 1 else: print(f"{self.name} misses the ball.") else: print(f"{self.name} misses the ball.") def display_score(self): print(f"{self.name}: {self.score} points") ``` 下面是游戏的主函数: ```python def play_game(): player1 = Player("Player 1") player2 = Player("Player 2") while True: player1.move() player2.move() player1.hit_ball(player2) player2.hit_ball(player1) player1.display_score() player2.display_score() if player1.score >= 5: print(f"{player1.name} wins!") break elif player2.score >= 5: print(f"{player2.name} wins!") break ``` 您可以运 `play_game()` 函数来开始游戏。希望这个程序符合您的要求!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值