目录
牛客_十字爆破_预处理+模拟
题目解析
C++代码
Java代码
牛客_十字爆破_预处理+模拟
十字爆破 (nowcoder.com)
描述:
牛牛在玩一个游戏:
一共有n行m列共n*m个方格,每个方格中有一个整数。
牛牛选择一个方格,可以得到和这个方格同行、同列的所有数之和的得分。
例如:对于一个2*2的方格:
1 2
3 4
牛牛选择每个方格的得分如下:
6 7
8 9
因为1+2+3=6,1+2+4=7,1+3+4=8,2+3+4=9。
现在牛牛想知道下一步选择每个格子的得分情况,你可以帮帮他吗?
题目解析
模拟即可,但是由于数据量过大,可以提前把每一行以及每一列的和存起来,方便统计总和。
C++代码
#include <iostream>
#include <vector>
using namespace std;
#define int long long
signed main()
{int n = 0, m = 0;cin >> n >> m;vector<vector<int>> vv(n, vector<int>(m));for (int i = 0; i < n; ++i){for (int j = 0; j < m; ++j){scanf("%lld", &vv[i][j]);}}vector<int> sum1(n); // 每一行的和for (int i = 0; i < n; ++i) // 每一行{for (int j = 0; j < m; ++j) // 每一列{sum1[i] += vv[i][j];}}// for(int i = 0; i < n; ++i)// {// cout << sum1[i] << " ";// }// cout << endl << endl;vector<int> sum2(m); // 每一列的和for (int j = 0; j < m; ++j) // 每一列{for (int i = 0; i < n; ++i) // 每一行{sum2[j] += vv[i][j]; // j i}}// for(int i = 0; i < n; ++i)// {// cout << sum2[i] << " ";// }// cout << endl << endl;vector<vector<int>> res(n, vector<int>(m));for (int i = 0; i < n; ++i){for (int j = 0; j < m; ++j){// res[i][j] = sum1[i] + sum2[j];// cout << sum1[i] + sum2[j] - vv[i][j] << " ";printf("%lld ", sum1[i] + sum2[j] - vv[i][j]);}printf("\n");}return 0;
}
Java代码
import java.util.*;
import java.io.*;public class Main
{public static Read in = new Read();//public static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));public static void main(String[] args) throws IOException{int n = in.nextInt(), m = in.nextInt();long[][] arr = new long[n][m];long[] row = new long[n];long[] col = new long[m];for(int i = 0; i < n; i++){for(int j = 0; j < m; j++){arr[i][j] = in.nextInt();row[i] += arr[i][j];col[j] += arr[i][j];}}for(int i = 0; i < n; i++){for(int j = 0; j < m; j++){System.out.print((row[i] + col[j] - arr[i][j]) + " ");}System.out.println("");}//out.close();}
}
class Read
{StringTokenizer st = new StringTokenizer("");BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));String next() throws IOException {while(!st.hasMoreTokens()){st = new StringTokenizer(bf.readLine());}return st.nextToken();}String nextLine() throws IOException {return bf.readLine();}int nextInt() throws IOException {return Integer.parseInt(next());}long nextLong() throws IOException {return Long.parseLong(next());}double nextDouble() throws IOException {return Double.parseDouble(next());}
}