P3573 [POI2014] RAJ-Rally
Glassy_Sky · · 个人记录
P3573 [POI2014] RAJ-Rally
题目:
给定一个
请找到一个点,使得删掉这个点后剩余的图中的最长路径最短。
分析:
可以注意到,本题给出的图是一个 DAG(有向无环图),这将是我们解决这道题的突破口。
基于 DAG 条件,先考虑对图进行 拓补排序。
思考一会,发现如果先删点,再找最长路径将会十分麻烦。
不如反向思考,考虑 将路径贡献到 删的点,再取最大值,就可以处理删点后最长路径长度的问题。
若删除节点
如果路径上有一条边
换句话说,就是 节点
接下来我们来证明这一点。
证明
根据拓补序(和 DAG)的性质,如果有边
回到正题,由于拓补序上节点
同理,由于拓补序上节点
而节点
证毕。
如果路径上有一条边
u → v ,满足在拓补序上 点u,v 在点t 的两侧,那么 此路径将不会因为节点t 被删而受到影响。
基于这点,我们就可以通过 枚举边
而贡献的节点
所以边
在最后我们对每个点再取个最大值,即删掉该点的最大路径长度。
这不就是区间维护最大值吗?!
线段树,启动!!!
最后我们在对每一个最大值取最小值,就是答案了。
修改加询问的 总复杂度:
但在你兴奋打完程序,运行测样例的时候 却发现输出了个 1 0,怎么回事呢?
发现是通过上述方法,永远贡献不到拓补序的左右端点。(历时半个小时)
考虑建立一个超级源点和一个超级汇点来垫一下左端和右端,将每个点和这两点连一个边,即可解决。
至于路径长度,通过预处理所有点 到源点和汇点的距离即可,对于每次枚举的边 dis_s[u]+dis_t[v]+1。
参考代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=5e5+5,maxm=1e6+5;
int n,m,in[maxn],out[maxn],topo[maxn],cnt=0,pos[maxn];
int u[maxm],v[maxm],dis_s[maxn],dis_t[maxn];
vector<int>edge[maxn],fedge[maxn];
struct Segment_Tree {
int maxx[maxn<<2];
bool tag[maxn<<2];
int minn=1e9,ans;
inline void pushdown(int spot) {
if(!tag[spot]) return ;
int lson=spot<<1,rson=lson|1;
maxx[lson]=max(maxx[spot],maxx[lson]);
maxx[rson]=max(maxx[spot],maxx[rson]);
tag[lson]=tag[rson]=true;
tag[spot]=false;
}
void update(int spot,int L,int R,const int& x,const int& y,const int& k) {
if(x<=L&&R<=y) {
if(maxx[spot]<k)
maxx[spot]=k,tag[spot]=true;
return ;
}
pushdown(spot);
int mid=(L+R)>>1,lson=spot<<1,rson=lson|1;
if(x<=mid) update(lson,L,mid,x,y,k);
if(mid<y) update(rson,mid+1,R,x,y,k);
}
void query(int spot,int L,int R) {
if(L==R) {
if(1<L&&L<n&&minn>maxx[spot])
minn=maxx[spot],ans=topo[L];
return ;
}
pushdown(spot);
int mid=(L+R)>>1,lson=spot<<1,rson=lson|1;
query(lson,L,mid);
query(rson,mid+1,R);
}
}T;
void init() { //预处理拓补序和到源汇点距离
queue<int>q;
q.push(n-1);
dis_s[n-1]=-1;
while(!q.empty()) {
int now=q.front();
q.pop();
pos[now]=++cnt;
topo[cnt]=now;
for(int i=0;i<edge[now].size();i++) {
int v=edge[now][i];
in[v]--;
if(!in[v]) {
q.push(v);
dis_s[v]=dis_s[now]+1;
}
}
}
q.push(n);
dis_t[n]=-1;
while(!q.empty()) {
int now=q.front();
q.pop();
for(int i=0;i<fedge[now].size();i++) {
int v=fedge[now][i];
out[v]--;
if(!out[v]) {
q.push(v);
dis_t[v]=dis_t[now]+1;
}
}
}
}
int main() {
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++) {
scanf("%d%d",&u[i],&v[i]);
edge[u[i]].push_back(v[i]);
fedge[v[i]].push_back(u[i]);
in[v[i]]++;
out[u[i]]++;
}
for(int i=1;i<=n;i++) {//加上源汇点并连边
u[m+i*2-1]=n+1,v[m+i*2-1]=i;
edge[n+1].push_back(i);
fedge[i].push_back(n+1);
in[i]++,out[n+1]++;
u[m+i*2]=i,v[m+i*2]=n+2;
edge[i].push_back(n+2);
fedge[n+2].push_back(i);
in[n+2]++,out[i]++;
}
m=m+n+n;
n=n+2;
init();
for(int i=1;i<=m;i++) {
int x=pos[u[i]]+1,y=pos[v[i]]-1;
if(x<=y)
T.update(1,1,n,x,y,dis_s[u[i]]+dis_t[v[i]]+1);
}
T.query(1,1,n);
printf("%d %d",T.ans,T.minn);
return 0;
}