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 進行提交了。

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