Gym - 100342I Travel Agency(割頂)

來源:互聯網
上載者:User

標籤:割頂   gym   

題意:給一個無向圖,對於每個節點a,統計有多少點對(u,v)之間的路徑必須經過a。

思路:首先求一個圖的割頂,在這顆dfs時間樹中我們可以發現,對於一個結點u,如果他的一顆子樹不能連回u以上的結點,那麼這一棵子樹的結點與除u以外的結點之間的路徑必然經過u,那麼在dfs的過程中不斷更新答案即可。

#include<cstdio>#include<cstring>#include<cmath>#include<cstdlib>#include<iostream>#include<algorithm>#include<vector>#include<map>#include<queue>#include<stack>#include<string>#include<map>#include<set>#include<ctime>#define eps 1e-6#define LL long long#define pii (pair<int, int>)//#pragma comment(linker, "/STACK:1024000000,1024000000")using namespace std;const int maxn = 25000;//const int INF = 0x3f3f3f3f;int n, m;int pre[maxn], ans[maxn], dfs_clock, cnt[maxn];vector<int> G[maxn];//無向圖的割頂和橋int dfs(int u, int fa) { //u在dfs樹中的父節點為fa int lowu = pre[u] = ++dfs_clock;ans[u] = 0; cnt[u] = 1;int sum = 0;for(int i = 0; i < G[u].size(); i++) {int v = G[u][i];if(!pre[v]) {   //沒有訪問過v int lowv = dfs(v, u);lowu = min(lowu, lowv);    //用後代的low函數更新u的low函數 cnt[u] += cnt[v];if(lowv >= pre[u]) {ans[u] += sum * cnt[v];sum += cnt[v];}}else if(pre[v] < pre[u] && v != fa)  lowu = min(lowu, pre[v]);  //用反向邊更新u的low函數 } ans[u] += (n-1-sum) * sum + n - 1;return lowu; } int main() {    freopen("travel.in", "r", stdin);    freopen("travel.out", "w", stdout);//freopen("input.txt", "r", stdin);cin >> n >> m;for(int i = 0; i < m; i++) {        int u, v; scanf("%d%d", &u, &v);        G[u].push_back(v);        G[v].push_back(u);}dfs(1, -1);for(int i = 1; i <= n; i++) printf("%d\n", ans[i]);    return 0;}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Gym - 100342I Travel Agency(割頂)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.