牛客网暑期ACM多校训练营(第八场)E Touring cities(哈密尔顿回路)

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

题目描述

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矩阵,格子为点,相邻格子连边,再给出K条边,问经过所有格子并回到出发点的环路多长

思路:容易得当n或者m其中一个为偶数的时候,一定有哈密尔顿回路的存在(汉密尔顿回路问题),当n和m都为奇数的时候,我们将矩阵填色,黑白相间,当存在一条路径,连接两个不同的黑格子的时候,存在哈密尔顿回路,证明看下面的题解。存在哈密尔顿回路,答案为n*m,不存在答案为n*m+1.

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
typedef long long ll;

int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		int n,m,k;
		scanf("%d%d%d",&n,&m,&k);
		int flag=0;
		while(k--){
			int a,b,c,d;
			scanf("%d%d%d%d",&a,&b,&c,&d);
			if(a==c&&b==d)continue;
			if(((a-1)*m+b)%2==1&&((c-1)*m+d)%2==1)flag=1;
		}
		if(n%2==0||m%2==0)printf("%d\n",n*m);
		else{
			if(flag)printf("%d\n",n*m);
			else printf("%d\n",n*m+1);
		}
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值