洛谷 P6559 [SBCOI2020]小镇 (ACM训练)

洛谷 P6559 [SBCOI2020]小镇 (ACM训练)_第1张图片
洛谷 P6559 [SBCOI2020]小镇 (ACM训练)_第2张图片
对于80%样例:

#include
#include
#include
#include
#include
#include
using namespace std;
const int MAXN = 1e5 + 5;
inline int read()
{
    int x = 0, f = 1; char c = getchar();
    while (c < '0' || c>'9') { if (c == '-')f = -1; c = getchar(); }
    while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
    return x * f;
}
int n, k, x[MAXN], y[MAXN], ans = 0;
int main()
{
    n = read(); k = read();
    printf("n: %d k: %d\n", n, k);
    for (int i = 1; i <= k; i++)
    {
        x[i] = read();
        y[i] = read(); //读入
    }
    for (int i = 1; i <= k; i++)
        for (int j = i + 1; j <= k; j++) //暴力枚举任意两个格子
        {
            if (abs(x[i] - x[j]) + abs(y[i] - y[j]) == 1) //判断相邻
                ans++;
        }
    cout << ans << endl;
    return 0;
}

字符串读取方法:

inline int read()
{
    int x = 0, f = 1; char c = getchar();
    while (c < '0' || c>'9') { if (c == '-')f = -1; c = getchar(); }
    while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
    return x * f;
}

矩阵相邻格判断:

    for (int i = 1; i <= k; i++)
        for (int j = i + 1; j <= k; j++) //暴力枚举任意两个格子
        {
            if (abs(x[i] - x[j]) + abs(y[i] - y[j]) == 1) //判断相邻
                ans++;
        }

对于100%数据:

struct node
{
    int x, y;
}a[MAXN];
bool cmp1(node a, node b)
{
    if (a.x != b.x) return a.x < b.x;
    else return a.y < b.y;
}
bool cmp2(node a, node b)
{
    if (a.y != b.y) return a.y < b.y;
    else return a.x < b.x;
} //排序函数
int n, k, ans;
int main()
{
    n = read(); k = read();
    for (int i = 1; i <= k; i++)
    {
        int x, y;
        x = read(); y = read();
        a[i].x = x; a[i].y = y;
    }
    sort(a + 1, a + k + 1, cmp1); //统计平行于x轴的边
    for (int i = 1; i < k; i++)
    {
        if (a[i].x == a[i + 1].x && a[i].y == a[i + 1].y - 1) //若x轴相同并且y轴差为1
            ans++;
    }
    sort(a + 1, a + k + 1, cmp2); //统计平行于y轴的边
    for (int i = 1; i < k; i++)
    {
        if (a[i].y == a[i + 1].y && a[i].x == a[i + 1].x - 1) //同上
            ans++;
    }
    cout << ans << endl;
    return 0; //qwq
}

你可能感兴趣的:(洛谷 P6559 [SBCOI2020]小镇 (ACM训练))