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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

Weights Assignment For Tree Edges 树,拓扑序(1500)

發布時間:2025/3/19 编程问答 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Weights Assignment For Tree Edges 树,拓扑序(1500) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.



題意 :

  • 給定n個結點的樹和序列bbbpppbib_ibi?表示i結點的父節點,其中broot=rootb_{root}=rootbroot?=root,現在要給樹上的每個邊賦權值,使得每個結點到根的距離distidist_{i}disti?滿足p的排序,即如果在p數組中,i點位置在j點前面,則disti<distjdist_{i}<dist_{j}disti?<distj?
  • 如果可行,輸出每條邊的權值,否則,輸出-1

思路 :

  • 因為每條邊都賦正值,那么考慮一個結點,它的排名不可能比父節點靠前,也就是說p數組滿足拓撲序
  • 對于p=[3,1,2,5,4]p=[3,1,2,5,4]p=[3,1,2,5,4],構造dist3=0dist_3=0dist3?=0第一個肯定是根結點),dist1=2,dist2=3,...,dist_1=2,dist_2=3, ... ,dist1?=2,dist2?=3,...,滿足枚舉的順序,這個是結點到根的距離,只要記錄一下父節點到根的距離,相減就是這個邊的權值
  • 因此,按照p數組的順序從第一個非根結點開始枚舉每個點,如果枚舉到的這個點的父節點排名比它低(dist數組值為-1),直接return輸出-1,否則,當前這個結點dist數組值為i,ans數組記錄這個點到父節點這條邊的邊權,就是當前這個點到根的距離減去父節點到根的距離
#include <iostream> #include <algorithm> #include <cstring> #include <vector> #include <unordered_set> #include <math.h> using namespace std;typedef long long ll; typedef pair<int, int> PII;#define endl '\n' #define fi first #define se second #define push_back #define rep(i, l, r) for (ll i = l; i <= r; i ++ )const int N = 2e5 + 10;int b[N], p[N]; int ans[N], dist[N]; // ans為i點到父節點的距離,即邊權;dist為i點到根結點的距離void solve() {int n; cin >> n;for (int i = 1; i <= n && cin >> b[i]; i ++ );for (int i = 1; i <= n && cin >> p[i]; i ++ );for (int i = 1; i <= n; i ++ ) ans[i] = dist[i] = -1; // 初始化!同時也可以標記該點是否已經被訪問過,相對排名ans[p[1]] = 0, dist[p[1]] = 0;for (int i = 2; i <= n; i ++ ){int j = p[i]; // 當前這個點if (dist[b[j]] == -1) return cout << -1 << endl, void();dist[j] = i;ans[j] = dist[j] - dist[b[j]];}for (int i = 1; i <= n; i ++ ) cout << ans[i] << " \n"[i == n]; }int main() {cin.tie(nullptr) -> sync_with_stdio(false);int _;cin >> _;while (_ -- )solve();return 0; } 與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的Weights Assignment For Tree Edges 树,拓扑序(1500)的全部內容,希望文章能夠幫你解決所遇到的問題。

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