1840: 混合图的欧拉回路
内存限制:256 MB
时间限制:1.000 S
评测方式:文本比较
命题人:
提交:13
解决:9
题目描述
The city executive board in Lund wants to construct a sightseeing tour by bus in Lund, so that tourists can see every corner of the beautiful city. They want to construct the tour so that every street in the city is visited exactly once. The bus should also start and end at the same junction. As in any city, the streets are either one-way or two-way, traffic rules that must be obeyed by the tour bus. Help the executive board and determine if it's possible to construct a sightseeing tour under these constraints.
输入
On the first line of the input is a single positive integer n, telling the number of test scenarios to follow. Each scenario begins with a line containing two positive integers m and s, 1 <= m <= 200,1 <= s <= 1000 being the number of junctions and streets, respectively. The following s lines contain the streets. Each street is described with three integers, xi, yi, and di, 1 <= xi,yi <= m, 0 <= di <= 1, where xi and yi are the junctions connected by a street. If di=1, then the street is a one-way street (going from xi to yi), otherwise it's a two-way street. You may assume that there exists a junction from where all other junctions can be reached.
输出
For each scenario, output one line containing the text "possible" or "impossible", whether or not it's possible to construct a sightseeing tour.
样例输入 复制
4
5 8
2 1 0
1 3 0
4 1 1
1 5 0
5 4 1
3 4 0
4 2 1
2 2 0
4 4
1 2 1
2 3 0
3 4 0
1 4 1
3 3
1 2 0
2 3 0
3 2 0
3 4
1 2 0
2 3 1
1 2 0
3 2 0
样例输出 复制
possible
impossible
impossible
possible
提示
图中既有无向边,又有有向边,圈套圈算法是无法解决这个问题的。
用网络流可以解决这个问题。顶点总数为 Ο(|V|+|E|) 的方法比较容易想到,下面介绍一种顶点总数 Ο(|V|) 的方法。把无向边随意定向,先计算顶点 v 有向边的出度-入度 diff,如果这个点关联的无向边数小于 diff,那么无解。加上随意定向的无向边,再次计算顶点 v 的出度-入度,如果为奇数,那么也无解。
构建新图 G',添加两个顶点源 s 和汇 t
如果 u 到 v 有一条定向的无向边,那么 c(u, v) = 1。
对于 v,设 w = (入度-出度)/2,如果 w > 0,那么令 c(v, t) = w;
如果 w < 0,那么令 c(s, v) = -w。
其余顶点间的边容量都为0
计算图 G' 的最大流,如果从 s 出发的每条边都漫流,那么就找到了一个解;否则就无解。对于不和 s 或 t 连接的顶点,其入度=出度;和 s 连接的顶点 v,有 c(s, v) 条边出去,把出边反向,则入度=出度;和 t 连接的顶点类似。
用网络流可以解决这个问题。顶点总数为 Ο(|V|+|E|) 的方法比较容易想到,下面介绍一种顶点总数 Ο(|V|) 的方法。把无向边随意定向,先计算顶点 v 有向边的出度-入度 diff,如果这个点关联的无向边数小于 diff,那么无解。加上随意定向的无向边,再次计算顶点 v 的出度-入度,如果为奇数,那么也无解。
构建新图 G',添加两个顶点源 s 和汇 t
如果 u 到 v 有一条定向的无向边,那么 c(u, v) = 1。
对于 v,设 w = (入度-出度)/2,如果 w > 0,那么令 c(v, t) = w;
如果 w < 0,那么令 c(s, v) = -w。
其余顶点间的边容量都为0
计算图 G' 的最大流,如果从 s 出发的每条边都漫流,那么就找到了一个解;否则就无解。对于不和 s 或 t 连接的顶点,其入度=出度;和 s 连接的顶点 v,有 c(s, v) 条边出去,把出边反向,则入度=出度;和 t 连接的顶点类似。