题目链接:https://vjudge.net/problem/Kattis-appallingarchitecture
题目大意
给定n*m的矩形,'.'表示空地,其他的表示一个建筑模块,让你求出不是空地的那些地方,组成的一个图形的重心,与最后一行横坐标相比,如果重心的横坐标比最后一行的最左面的横坐标小,输出"left",比最右面的大,输出"right",否则输出"balanced"。
分析
这个题主要是求重心, 重心求出来就简单了。重心的公式:x = (w1*x1+w2*x2...+wn*xn) / n,wi是权重,xi是到y轴的距离。就是不太理解为什么最后要四舍五入,而不能直接用double。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int n, m;
char mp[110][110];
int main()
{
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++)
scanf("%s", mp[i] + 1);
int num = 0, ans = 0;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
if(mp[i][j] != '.')
{
ans += j;
num++;
}
}
}
int l = 1e9, r = 0;
for(int j = 1; j <= m; j++)
{
if(mp[n][j] != '.')
{
l = min(l, j);
r = max(r, j);
}
}
double ans1;
ans1 = ans;
ans1 /= num;
int ans2 = ans1 + 0.5;
if(ans2 < l) printf("left\n");
else if(ans2 > r) printf("right\n");
else printf("balanced\n");
return 0;
}