题目描述
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.
输入
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条桥,连接k对点,从一个点出发可以向四个方向走,也可以走桥直接到达对面的点。问从左上角出发,将所有方格访问一遍且回到原点,问最少需要多少步。
思路:先画一下图就可以发现,访问的步数只有两种n*m和n*m+1,。
sum=n*m
1,当sum为偶数时,访问步数为n*m。
2,当sum为奇数时,将棋盘黑白染色,规定左上角的格子是黑色。此时黑色比白色多1,且如果在上面走不走桥的情况下,一定是一黑一白,如果是黑出发必定回到此点前是在白点上,也就是说在不走桥的情况下无法n*m步走完,但只要有一个桥是从白点到另一个白点就可以n*m步走完。
代码:
int n,m,k,flag,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);
tmp=a*m+b;
cnt=c*m+d;
if(tmp!=cnt)
{
if(cnt%2==0&&tmp%2==0) flag=0;
}
}
printf("%d\n",n*m+flag);
}
return 0;
}