牛客网暑期ACM多校训练营(第八场) E Touring cities(棋盘染色)

本文介绍了一道牛客网ACM竞赛题“Touringcities”的解题思路及代码实现。题目要求从起点遍历所有城市并返回起点,考虑了铁路和航空公司之间的旅行。文章详细解释了如何通过分析城市布局和航线特点来找到最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:https://www.nowcoder.com/acm/contest/146/E
来源:牛客网
 

Touring cities

时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

Niuniu wants to tour the cities in Moe country. Moe country has a total of n*m cities. The positions of the cities form a grid with n rows and m columns. We represent the city in row x and column y as (x,y). (1 ≤ x ≤ n,1 ≤ y ≤ m) There are bidirectional railways between adjacent cities. (x1,y1) and (x2,y2) are called adjacent if and only if |x1-x2|+|y1-y2|=1. There are also K bidirectional air lines between K pairs of cities. It takes Niuniu exactly one day to travel by a single line of railway or airplane. Niuniu starts and ends his tour in (1,1). What is the minimal time Niuniu has to travel between cities so that he can visit every city at least once?

Note that the air line may start and end in the same city.

输入描述:

 

The first line contains oneinteger T(T≤20), which means the number of test cases.

Each test case has the format as described below.

n m K

ax1 ay1 bx1 by1
ax2 ay2 bx2 by2

axK ayK bxK byK

(0 ≤ K ≤ 10. 2 ≤ n,m ≤ 100, 1 ≤ n*m ≤ 100)

There is one bidirectional air line between (axi,ayi) and (bxi,byi). (1 ≤ axi,bxi ≤ n , 1 ≤ ayi,byi ≤ m)

 

输出描述:

For each test case,print one number in a single line, which is the minimal number of days Niuniu has to travel between cities so that he can visit every city at least once.

示例1

输入

复制

3
2 2 1
1 1 2 2
3 3 1
1 1 3 3
3 3 0

输出

复制

4
9
10

备注:

The air line may start and end in the same city.

题意:给你一个n*m的棋盘,你要从(1,1)出发遍历整个棋盘再回到(1,1),图中某些格子可以直接飞到另一个格子。求最少走多少步回到(1,1)且遍历整个棋盘。

思路:昨天刚看的棋盘染色问题。。。今天就用上了。。。首先容易想到,当n*m为偶数时,答案就是n*m。因为正好可以有一个哈密顿回路。当n,m均为奇数时,对棋盘进行黑白染色,黑白相间给每个格子染色,即从(1,1)出发再回到(1,1)。由于n,m均为奇数时,白色的格子比黑色的格子数多1,我们从白色的格子(1,1)出发,在黑色格子(1,2)或(2,1)返回,不可能有一条路径使路径上的白色格子数大于黑色格子数。但是,如果有任意一个飞机可以从白格子飞到另一个非自己的白格子就可以了。因此判断一下即可。

代码:

#include<bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define mo 998244353
using namespace std;
using namespace std;
const int maxn=562145;
int n,m,q,k,flag,x,f,y,p,a,b,c,d;
int tmp,cnt;
int main(){
    int T,cas=1;
    scanf("%d",&T);
        while(T--){
        flag=1;
        scanf("%d%d%d",&n,&m,&k);
        if(n*m%2==0) {flag=0;}
        while(k--){
        scanf("%d%d%d%d",&a,&b,&c,&d);
        if(a==c&&b==d) continue;
        tmp=(a+b)&1;
        cnt=(c+d)&1;
        if(!tmp&&!cnt)flag=0;
        }
        printf("%d\n",n*m+flag);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值