日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

CodeForces - 1301E 1-Trees and Queries(LCA)

發布時間:2024/4/11 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 CodeForces - 1301E 1-Trees and Queries(LCA) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目鏈接:點擊查看

題目大意:給出一棵樹,再給出 m 次詢問,每次詢問給出 x , y , a , b , k ,問如果在點 x 和點 y 之間添加一條邊,那么能否從點 a 到點 b 恰好走 k 條邊到達,樹上的邊和點都可以重復經過

題目分析:讀完題后沒什么思路,但其實稍微轉換一下題意就變的非常簡單了,題目要求恰好經過 k 條邊從點 a 到達點 b ,那么我們思考一下有哪些途徑可以從點 a 到達點 b 呢?

  • 直接從點 a 到達點 b?
  • a -> x -> y -> b
  • a -> y -> x -> b
  • 其實仔細一想無非只有這三條路可走,每條路徑的長度也可以用樹上倍增求LCA在logn的時間內解決,現在問題是如何恰好走 k 步呢?其實直接從點 a 到達點 b 后,根據剩余的步數判斷就可以了,因為如果剩余的步數為偶數的話,我們可以在點 b 和旁邊任意一個點之間反復橫跳,最后步數可以恰好抵消掉,相應的,剩余步數為奇數時就不能抵消了

    代碼:

    #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<unordered_map> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=1e5+100;vector<int>node[N];int deep[N],dp[N][20],limit;void dfs(int u,int fa,int dep) {deep[u]=dep;dp[u][0]=fa;for(int i=1;i<=limit;i++)dp[u][i]=dp[dp[u][i-1]][i-1];for(auto v:node[u]){if(v!=fa)dfs(v,u,dep+1);} }int LCA(int x,int y) {if(deep[x]<deep[y])swap(x,y);for(int i=limit;i>=0;i--)if(deep[x]-deep[y]>=(1<<i))x=dp[x][i];if(x==y)return x;for(int i=limit;i>=0;i--)if(dp[x][i]!=dp[y][i]){x=dp[x][i];y=dp[y][i];}return dp[x][0]; }int dis(int a,int b) {int lca=LCA(a,b);return deep[a]+deep[b]-2*deep[lca]; }int main() { //#ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); //#endif // ios::sync_with_stdio(false);int n;scanf("%d",&n);limit=log2(n)+1;for(int i=1;i<n;i++){int u,v;scanf("%d%d",&u,&v);node[u].push_back(v);node[v].push_back(u);}dfs(1,0,0);int m;scanf("%d",&m);while(m--){int x,y,a,b,k;scanf("%d%d%d%d%d",&x,&y,&a,&b,&k);int d1=dis(a,b),d2=dis(a,x)+dis(b,y)+1,d3=dis(b,x)+dis(a,y)+1;if(k>=d1&&(k-d1)%2==0||k>=d2&&(k-d2)%2==0||k>=d3&&(k-d3)%2==0)puts("YES");elseputs("NO");}return 0; }

    ?

    總結

    以上是生活随笔為你收集整理的CodeForces - 1301E 1-Trees and Queries(LCA)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。