P3119 [USACO15JAN]草鉴定Grass Cownoisseur
题目描述
In an effort to better manage the grazing patterns of his cows, Farmer John has installed one-way cow paths all over his farm. The farm consists of N fields, conveniently numbered 1..N, with each one-way cow path connecting a pair of fields. For example, if a path connects from field X to field Y, then cows are allowed to travel from X to Y but not from Y to X.
Bessie the cow, as we all know, enjoys eating grass from as many fields as possible. She always starts in field 1 at the beginning of the day and visits a sequence of fields, returning to field 1 at the end of the day. She tries to maximize the number of distinct fields along her route, since she gets to eat the grass in each one (if she visits a field multiple times, she only eats the grass there once).
As one might imagine, Bessie is not particularly happy about the one-way restriction on FJ's paths, since this will likely reduce the number of distinct fields she can possibly visit along her daily route. She wonders how much grass she will be able to eat if she breaks the rules and follows up to one path in the wrong direction. Please compute the maximum number of distinct fields she can visit along a route starting and ending at field 1, where she can follow up to one path along the route in the wrong direction. Bessie can only travel backwards at most once in her journey. In particular, she cannot even take the same path backwards twice.
约翰有n块草场,编号1到n,这些草场由若干条单行道相连。奶牛贝西是美味牧草的鉴赏家,她想到达尽可能多的草场去品尝牧草。
贝西总是从1号草场出发,最后回到1号草场。她想经过尽可能多的草场,贝西在通一个草场只吃一次草,所以一个草场可以经过多次。因为草场是单行道连接,这给贝西的品鉴工作带来了很大的不便,贝西想偷偷逆向行走一次,但最多只能有一次逆行。问,贝西最多能吃到多少个草场的牧草。
输入格式
INPUT: (file grass.in)
The first line of input contains N and M, giving the number of fields and the number of one-way paths (1 <= N, M <= 100,000).
The following M lines each describe a one-way cow path. Each line contains two distinct field numbers X and Y, corresponding to a cow path from X to Y. The same cow path will never appear more than once.
输入:
第一行:草场数n,道路数m。
以下m行,每行x和y表明有x到y的单向边,不会有重复的道路出现。
输出格式
OUTPUT: (file grass.out)
A single line indicating the maximum number of distinct fields Bessie
can visit along a route starting and ending at field 1, given that she can
follow at most one path along this route in the wrong direction.
输出:
一个数,逆行一次最多可以走几个草场。
输入输出样例
输入 #1复制
输出 #1复制
说明/提示
SOLUTION NOTES:
Here is an ASCII drawing of the sample input:
v---3-->6
7 | \ |
^\ v \|
| \ 1 |
| | v
| v 5
4<--2---^
Bessie can visit pastures 1, 2, 4, 7, 2, 5, 3, 1 by traveling
backwards on the path between 5 and 3. When she arrives at 3 she
cannot reach 6 without following another backwards path.
思路:
首先用tarjian缩点,缩点后是一个有向无环图。每一个点的点权是他所在的SCC中节点的个数。
然后从一号节点所在的scc块进行SPFA找最长路,可以得到dis1[i] 代表从1所在联通块为始点走到scc_i的最大权值。
然后反向建边跑最长路,可以得到dis1[i] 代表从i所在联通块scc_i为始点,scc_1 为终点的最大权值。
然后枚举所有scc_i,如果scc_1可以到达scc_i,且 有scc_j为起点到scc_i 为终点的边,scc_j可以到达scc_1,则尝试逆行该边,更新答案,维护最大值。
代码:
#include
#include
#include
#include
#include
#include
#include
#include