CodeForces 629A-Far Relative’s Birthday Cake(枚举/暴力)

题目描述:

Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!

The cake is a n×n n×n n×n square consisting of equal squares with side length 1 1 1 . Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?

Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.

输入:

In the first line of the input, you are given a single integer n n n ( 1<=n<=100 1<=n<=100 1<=n<=100 ) — the length of the side of the cake.

Then follow n n n lines, each containing n n n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.

输出:

Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column. 

样例输入1: 

3

.CC

C..

C.C  

样例输出1: 

样例输入2: 

4

CC..

C..C

.CC.

.CC.  

样例输出2: 

9

题目大意 and 解题思路: 

蛋糕是一个由 n×n 的正方形组成的形状,长度为1。每个方块要么是空的,要么是由一个巧克力组成的。他们买了蛋糕,便开始把巧克力放在蛋糕上。“家庭之门”的幸福值等于蛋糕中同一行或同一列中装有巧克力的一对细胞的数量。多尔的家人想知道他们的幸福程度是多少?

第一行输入一个整数n(1<=n<=100),表示蛋糕边的长度。然后输入n行数,每行有n个字符。空的细胞用'.'表示,而含有巧克力的细胞用“C”表示。

输出“家庭之门”幸福感的价值,即同一行或同一列的一对巧克力片的数量。

这道题直接遍历就可以了,用一个数c去记录一行或一列中巧克力的数量,t来表示“家庭之门”幸福感的价值,那么在某一行或者是某一列中,任意两个字符 'C' 就算是构成了一对巧克力,相应的价值加1,所以:

当c=1时,t=0;当c=2时,t=1;当c=3时,t=3;当c=4时,t=6......我们会发现一个规律:t=(c*(c-1))/2

你也可以理解成:一个包含n个结点的无向图中,可以包含的边数。

AC Code: 

#include<bits/stdc++.h>
using namespace std;
int main() {
	int n,sum=0,a=0,b=0;
	char s[101][101];
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
			scanf(" %c",&s[i][j]);//%前面有个空格,保证完整输入
	for(int i=1;i<=n;i++) {//横向遍历
		a=0;
		for(int j=1;j<=n;j++) {
			if(s[i][j]=='C')
				a++;
		}
		sum+=(a*(a-1))/2;
	}
	for(int j=1;j<=n;j++) {//纵向遍历
		b=0;
		for(int i=1;i<=n;i++) {
			if(s[i][j]=='C')
				b++;
		}
		sum+=(b*(b-1))/2;
	}
	printf("%d\n",sum);
	return 0;
} 

本题虽然是在洛谷上面提交的,但是题目来源在 CodeForces 上,所以博主就直接在 CodeForces 进行提交了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章