一道水题,但是在编码的时候居然卡住了,收集了一些写法,还满有趣的。
我自己的
vector
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 1e5 + 7; const ll mod = 1e9 + 7; inline ll read() { ll s = 0, f = 1; char ch; do { ch = getchar(); if (ch == '-') f = -1; } while (ch < 48 || ch > 57); while (ch >= 48 && ch <= 57) s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar(); return s * f; } vector<vector<ll>> a; int main() { vector<ll> line; ll n = read(), m = read(); for (int i = 0; i < n; ++i) { vector<ll> aa; ll x, sum = 0; for (int j = 0; j < m; ++j) { x = read(); aa.push_back(x); sum += x; } line.push_back(sum); a.push_back(aa); } vector<ll> row; for (int j = 0; j < m; ++j) { ll sum = 0; for (int i = 0; i < n; ++i) sum += a[i][j]; row.push_back(sum); } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) printf("%lld ", line[i] + row[j] - a[i][j]); printf("\n"); } return 0; }
YWG的
我觉得是最好的
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e6 + 7; inline ll read() { ll s = 0, f = 1; char ch; do { ch = getchar(); if (ch == '-') f = -1; } while (ch < 48 || ch > 57); while (ch >= 48 && ch <= 57) s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar(); return s * f; } ll x[maxn], y[maxn], tmp; int main() { ll n=read(), m=read(); ll Map[n + 1][m + 1]; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { Map[i][j]=read(); x[i] += Map[i][j]; y[j] += Map[i][j]; } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) printf("%lld ", x[i] + y[j] - Map[i][j]); printf("\n"); } return 0; }
青竹大佬的
#include <bits/stdc++.h> using namespace std; const int maxn = 3e5 + 7; typedef long long ll; int n, m; vector<int> v[1000000]; vector<ll> H, L; int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) { ll sum = 0; for (int j = 1, x; j <= m; j++) { scanf("%d", &x); v[i].push_back(x); sum += x; } H.push_back(sum); } for (int j = 1; j <= m; j++) { ll sum = 0; for (int i = 1; i <= n; i++) { sum += v[i][j - 1]; } L.push_back(sum); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { ll ans = H[i - 1] + L[j - 1] - v[i][j - 1]; printf("%lld ", ans); } printf("\n"); } }
出题人的
知识点:预处理。
思路:开两个数组分别处理每一行的和以及每一列的和。之后对应顶点输出(对应行+对应列-该顶点)即可。
这道题更难的地方是n和m大小未定。解决方法有两种,一个是动态内存(malloc或者vector),另一种方法是用一维数组代替二维数组(a[i][j]和a[i*m+j]等价)。这里标程用的是第二种方法。
标程代码:
#include<bits/stdc++.h> using namespace std; #define ll long long ll a[1000010]; ll sr[1000010],sc[1000010]; int main(){ int n,m,i; cin>>n>>m; for(i=0;i<n*m;i++)scanf("%lld",&a[i]); for(i=0;i<n*m;i++){ sr[i/m]+=a[i]; sc[i%m]+=a[i]; } for(i=0;i<n*m;i++){ printf("%lld ",sr[i/m]+sc[i%m]-a[i]); if(i%m==m-1)printf("\n"); } }