POJ 3417 Network

來源:互聯網
上載者:User

標籤:

每條額外的邊加入到圖中,會導致樹上一條路徑成環,假設沒有其餘邊,那麼要將新圖分成兩部分,如果想刪一條成環路徑上的邊,那麼必須把這條額外邊也刪除。

因此每條額外邊加入時,只需將環上的邊+1。最後看看每條邊被加了幾次,被加了x次,也就是說刪除這條邊,至少還要刪除x條邊才能被分成兩半,如果一次都沒有被加,意味著這條邊刪了就分成兩半了,對答案的貢獻為m;如果被加了一次,那麼對答案的貢獻為1;如果被加的次數超過1,那麼對答案沒有貢獻。

#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>#include<vector>#include<map>#include<set>#include<queue>#include<stack>#include<iostream>using namespace std;typedef long long LL;const double pi=acos(-1.0),eps=1e-8;void File(){    freopen("D:\\in.txt","r",stdin);    freopen("D:\\out.txt","w",stdout);}inline int read(){    char c = getchar();  while(!isdigit(c)) c = getchar();    int x = 0;    while(isdigit(c)) { x = x * 10 + c - ‘0‘; c = getchar(); }    return x;}const int maxn=100000+10;int n,m,cnt,h[maxn],f[maxn];struct Edge{int to,nx;}e[2*maxn];bool flag[maxn];void AddEdge(int u,int v){    e[cnt].to=v; e[cnt].nx=h[u]; h[u]=cnt++;}void dfs(int x){    flag[x]=1;    for(int i=h[x];i!=-1;i=e[i].nx)    {        if(flag[e[i].to]) continue;        dfs(e[i].to); f[x]=f[x]+f[e[i].to];    }}int F[2*maxn],B[2*maxn],pos[maxn];int rmq[maxn*2][20],done;void DFS(int u,int p,int dep){    F[++done]=u,B[done]=dep;    pos[u]=done;    for(int son=h[u];son!=-1;son=e[son].nx)    {        int v=e[son].to;        if(v==p)continue;        DFS(v,u,dep+1);        F[++done]=u,B[done]=dep;    }}void initRMQ(){    for(int i=1;i<=done;i++)rmq[i][0]=i;    for(int j=1;(1<<j)<=done;j++)        for(int i=1;i+(1<<j)-1<=done;i++)            if(B[rmq[i][j-1]]<B[rmq[i+(1<<(j-1))][j-1]])rmq[i][j]=rmq[i][j-1];            else rmq[i][j]=rmq[i+(1<<(j-1))][j-1];}int LCA(int a,int b){    a=pos[a],b=pos[b];    if(a>b)swap(a,b);    int k=log(1.0+b-a)/log(2.0);    if(B[rmq[a][k]]<B[rmq[b-(1<<k)+1][k]])return F[rmq[a][k]];    else return F[rmq[b-(1<<k)+1][k]];}int main(){    scanf("%d%d",&n,&m);    done=cnt=0; memset(h,-1,sizeof h);    for(int i=0;i<n-1;i++)    {        int u,v; scanf("%d%d",&u,&v);        AddEdge(u,v); AddEdge(v,u);    }    DFS(1,1,0);  initRMQ();    for(int i=1;i<=m;i++)    {        int u,v; scanf("%d%d",&u,&v);        f[u]++; f[v]++; f[LCA(u,v)]-=2;    }    dfs(1); int ans=0;    for(int i=2;i<=n;i++)    {        if(f[i]==0) ans=ans+m;        else if(f[i]==1) ans=ans+1;    }    printf("%d\n",ans);    return 0;}

 

POJ 3417 Network

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.