$题解 CF629A 【Far Relative’s Birthday Cake】 $

一道简单的问题,我们一步一步来解决。


\[First:\text{输入}\]
输入十分简单,首先,\(cin>>n\),输入\(n\)之后,两重\(for\)循环,将题目所要输入的矩阵输进去,像这样\(↓↓↓\)

    for(int i=1;i<=n;i++)
     for(int j=1;j<=n;j++)
      cin>>ch[i][j];  

注意了,\(ch[][]\)应该是一个字符类型\((char)\)的数组


\[Second:\text{解决问题}\]
根据题意,\(C\)就是含有巧克力的细胞,我们可以用两个双重\(for\)循环,一遍遍历每一个竖列,一遍遍历每一个横列。,用\(c\)来表示一共有几对巧克力的细胞,\(t\)来表示“家庭之门”幸福感的价值,根据
\[\text{当}c=1\text{时}\ ,t=0\]
\[\text{当}c=2\text{时}\ ,t=1\]
\[\text{当}c=3\text{时}\ ,t=3\]
\[\text{当}c=4\text{时}\ ,t=6\]
\[\text{当}c=5\text{时}\ ,t=10\]
根据数学方法,可得\(\huge t=\frac{c\times(c-1)}{2}\)应为要统计每一行/列\(t\)的个数,所以,可用以下方法遍历矩阵\(↓↓↓\)

    for(int i=1;i<=n;i++)
    {
        c=0;   //初始化
        for(int j=1;j<=n;j++)
        {
            if(ch[i][j]=='C')
            c++;
        }
        t+=(c*(c-1))/2;  //更新t的值
    }
    for(int j=1;j<=n;j++)
    {
        c=0;   //初始化
        for(int i=1;i<=n;i++)
        {
            if(ch[i][j]=='C')
            c++;
        }
        t+=(c*(c-1))/2;  //更新t的值
    }

最后\(cout<<t\)即可。


\(My \ complete \ code:\)

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n,t=0,c=0; //初始化
    char ch[105][105];
    cin>>n;
    for(int i=1;i<=n;i++)
     for(int j=1;j<=n;j++)
      cin>>ch[i][j];   //输入
    for(int i=1;i<=n;i++)
    {
        c=0;
        for(int j=1;j<=n;j++)
        {
            if(ch[i][j]=='C')
            c++;
        }
        t+=(c*(c-1))/2;
    }            //横向遍历
    for(int j=1;j<=n;j++)
    {
        c=0;
        for(int i=1;i<=n;i++)
        {
            if(ch[i][j]=='C')
            c++;
        }
        t+=(c*(c-1))/2;
    }          //竖向遍历
    cout<<t;
}

猜你喜欢

转载自www.cnblogs.com/Luke-Skywalker/p/11295858.html