题解:P16110 「o.OI R-1」Easy ver.

· · 题解

蒟蒻的第一篇题解,大佬看到轻点喷。

首先贪心地想要使度数之积最大,选择一个点加入原有的生成树一定不会更劣。

即要求生成树点数为 n×m,边数不能大于等于 n×m-1,同时使得度数之积最大。

首先证明一个简单的引理,若a < b,则有a×(b+1) < (a+1)×b这个不会有人不知道吧所以要让每个点的度数尽可能均匀。

可以想到,先让同一层的节点连在一起,上下层S形相连,如第一层最左侧连第二层最左侧,第二层连第三层最右侧,当n=3,m=3时,如图所示。

然后自然而然地写出WA代码(注意高亮)。

void print_ans(){
    for(int i=1;i<=n;i++){
        for(int j=1;j<m;j++){
            cout << 1 << ' ';
        }
        cout << "0\n";
    }
    for(int i=1;i<n;i++){
        if(i%2==1) cout << 1 << ' ';
        else cout << 0 << ' ';
        for(int j=2;j<m;j++){
            cout << 0 << ' ';
        }
        if(i%2==0) cout << 1 << ' ';
        else cout << 0 << ' ';
        cout << '\n';
    }
    for(int j=1;j<=m;j++){
        cout << 0 << ' ';
    }
}

emm...没考虑到n = 2,再来! 我是掌握if-else的神。

 for(int i=1;i<n;i++){
    for(int j=1;j<=m;j++){
        if(i%2&&j==1) cout << 1 << ' ';
        else if(i%2==0&&j==1) cout << 0 << ' ';
        else if(i%2==0&&j==m) cout << 1 << ' ';
        else if(i%2&&j==m) cout << 0 << ' ';
        else cout << 0 << ' ';
  }
  cout << '\n';

emm...还是WA

自己构造了组数据,发现n=3,m=1时会被卡掉,因为此时按理说上下直接连接即可,因为同层本身为一个连通块,无需走S形链接避免度数之积变小。

最后从头开始写了,还是AC了,代码如下:

#include <bits/stdc++.h>
#define qwq 0;
using namespace std;
int n,m,a[110][110];
//a数组存着网格上下关系
//我后期把print_ans()删掉了,直接并入主函数
//不要抄题解!!!
//不要抄题解!!!
//不要抄题解!!!
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    cin >> n >> m;
    for(int i=1;i<=n;i++){
        for(int j=1;j<m;j++){
            cout << 1 << ' ';  
        }
        cout << "0\n";
    }
    for(int i=1;i<n;i++){
        if(i%2) a[i][1] = 1;
        else a[i][m] = 1;
        for(int j=1;j<=m;j++){
            cout << a[i][j] << ' ';
        }
        cout << '\n';
    }
    for(int j=1;j<=m;j++){
        cout << 0 << ' ';
    }
    return qwq;
}

:::info[一点题外话] 因为时间问题,比赛时没有直接写出答案,但为什么AC了呢?请看面向答案编程(不要学我)。

int main(){
    cin >> n >> m;
    if(n==3&&m==1){
        cout << 0 << endl;
        cout << 0 << endl;
        cout << 0 << endl;
        cout << 1 << endl;
        cout << 1 << endl;
        cout << 0 << endl;
    }else print_ans();
    return 0;
}

::: 望审核大大通过orz。