【学校联考】CQYZ_Vijos_P3755 轰炸

来源:互联网 发布:免费开单软件 编辑:程序博客网 时间:2024/04/25 22:39

【问题描述】

  战狂也在玩《魔方王国》。他只会征兵而不会建城市,因此他决定对小奇的城市进行轰炸。
  小奇有 n 座城市,城市之间建立了 m 条 有向的地下通道。战狂会发起若干轮轰炸,每轮可以轰炸任意多个城市。
  每座城市里都有战狂部署的间谍,在城市遭遇轰炸时,它们会通过地下通道撤离至其它城市。非常不幸的是,在地道里无法得知其它城市是否被轰炸,如果存在两个不同的城市 i,j,它们在同一轮被轰炸,并且可以通过地道从城市 i 到达城市 j,那么城市 i 的间谍可能因为撤离到城市 j 而被炸死。为了避免这一情况,战狂不会在同一轮轰炸城市 i 和城市 j。
  你需要求出战狂最少需要多少轮可以对每座城市都进行至少一次轰炸。

【输入格式】

  第一行两个整数 n,m。接下来 m 行每行两个整数 a,b 表示一条从 a 连向 b的单向边。

【输出格式】

  输出一行,仅一个整数表示答案。

【输入样例】

5 4
1 2
2 3
3 1
4 5

【输出样例】

3

【数据范围】

  对于 20%的数据,n,m<=10。
  对于 40%的数据,n,m<=1000。
  对于另外 30%的数据,保证无环。
  对于 100%的数据,n,m<=1000000。

题解:

  这道题最大的困难是读题。。。班上大部分人理解成了“i与j不能有边相连”,而且样例也不强(据说子集生成都能过样例),最后基本上都爆零了,事实上正确的理解是“i不能到达j”,也就是从i出发遍历不到j的意思
  理解题意后,发现是一道简单题(亏了亏了亏了),强连通分量缩点后求DAG图上的最长链就可以了
  真的特别讨厌这种代码量大的题,一不小心就要出错

#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>#include<cmath>using namespace std;typedef long long ll;const int maxn=1000005,maxm=1000005;int st[maxn]={0},top=0;struct edge{    int to,next;}e[maxm],E[maxm];int first[maxn]={0},np=0;int First[maxn]={0},Np=0;int dfn[maxn]={0},low[maxn]={0},dfs_clock=0;int scc=0,belong[maxn]={0},sz[maxn]={0},cd[maxn]={0};int d[maxn]={0};int n,m;inline int in(){    int x=0,f=1;char ch=getchar();    while(ch<'0'|ch>'9'){if(ch=='-') f=-f;ch=getchar();}    while(ch<='9'&&ch>='0') x=x*10+ch-'0',ch=getchar();    return x*f;}void addedge(int u,int v){e[++np]=(edge){v,first[u]},first[u]=np;}void Addedge(int u,int v){E[++Np]=(edge){v,First[u]},First[u]=Np;}void DFS(int i){         //Tarjan    dfn[i]=low[i]=++dfs_clock;    st[++top]=i;    for(int p=first[i];p;p=e[p].next){        int j=e[p].to;        if(dfn[j]){            if(!belong[j]) low[i]=min(low[i],dfn[j]);            continue;        }        DFS(j);        low[i]=min(low[i],low[j]);    }    if(low[i]==dfn[i]){        scc++;        while(1){            int x=st[top--];            belong[x]=scc,sz[scc]++;            if(x==i) break;        }    }}int dp(int i){    if(d[i]) return d[i];    if(!cd[i]) return d[i]=sz[i];    int ret=1;    for(int p=First[i];p;p=E[p].next){        int j=E[p].to;        ret=max(ret,dp(j)+sz[i]);    }    return d[i]=ret;}int main(){    n=in(),m=in();    int u,v;    for(int i=1;i<=m;i++){        u=in(),v=in();        addedge(u,v);    }/*..............强连通分量缩点压缩成新图...........................................*/    for(int i=1;i<=n;i++) if(!dfn[i]) DFS(i);    for(int i=1;i<=n;i++) for(int p=first[i];p;p=e[p].next){        int j=e[p].to;        if(belong[i]!=belong[j]){            Addedge(belong[i],belong[j]);            cd[belong[i]]++;        }    }/*..............按拓扑序记忆化搜索.................................................*/    int ans=0;    for(int i=1;i<=scc;i++) ans=max(ans,dp(i));    printf("%d",ans);    return 0;}
原创粉丝点击