Network of Schools POJ - 1236 tarjan强连通分量缩点
生活随笔
收集整理的這篇文章主要介紹了
Network of Schools POJ - 1236 tarjan强连通分量缩点
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
You are to write a program that computes the minimal number of schools that must receive a copy of the new software in order for the software to reach all schools in the network according to the agreement (Subtask A). As a further task, we want to ensure that by sending the copy of new software to an arbitrary school, this software will reach all schools in the network. To achieve this goal we may have to extend the lists of receivers by new members. Compute the minimal number of extensions that have to be made so that whatever school we send the new software to, it will reach all other schools (Subtask B). One extension means introducing one new member into the list of receivers of one school.?
題解:
題目第一句話說所有的電腦都是相互連接的,所以不用擔心出現森林的情況。
第一步用tarjan進行縮點,重新構圖得到一棵樹,然后統計樹上各點的入度以及出度。
記in為入讀為0的點,記out為出度為0的點。
那么我們很顯然的要給所有入度為0的點全都分配一套軟件,因為他們無法從別的地方得到軟件。
所以第一問的答案就是in。
考慮第二問,如果out > in 的話,我們從所有的出度為0的點開始連一條邊到入度為0的點去,這樣的話,入讀為0的點一定會被覆蓋,而且有的點甚至有多余1條入邊,這無所謂。所以我們只需要添加out條邊就可以了。
如果in > out的話,同理。
因此我們添加的邊的條數應該為max(in,out)
代碼:
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <set> using namespace std; const int MAXN = 107; int head[MAXN]; int cnt; int DFN[MAXN]; int LOW[MAXN]; int visit[MAXN]; int scc[MAXN]; int belong[MAXN]; int stk[MAXN];int sp; int index; int sccnum; struct edge{ int v; int next; int cost; }Es[10007]; void init(){ sp = sccnum = index = cnt = 0; memset(head,-1,sizeof(head)); memset(visit,0,sizeof(visit)); memset(belong,0,sizeof(belong)); } inline void add_edge(int i,int j,int cost){ Es[cnt].v = j; Es[cnt].cost = cost; Es[cnt].next = head[i]; head[i] = cnt++; } void tarjan(int u){DFN[u] = LOW[u] = ++index;visit[u] = 1;stk[sp++] = u; for(int e = head[u];e != -1;e = Es[e].next){int v = Es[e].v;if(!DFN[v]){tarjan(v);LOW[u] = min(LOW[u],LOW[v]);}else if(visit[v]){LOW[u] = min(LOW[u],DFN[v]);}}if(DFN[u] <= LOW[u]){//sccnum++;int top;do{top = stk[--sp];belong[top] = sccnum;visit[top] = 0;}while(top != u);} }int main() {init();int N;scanf("%d",&N);for(int i = 1;i <= N;i++){int num;while(scanf("%d",&num) && num){add_edge(i,num,1);}}for(int i = 1;i <= N;i++){if(!DFN[i])tarjan(i);}set<int> st1,st2;for(int i = 1;i <= N;i++){for(int e = head[i];e != -1;e = Es[e].next){int v = Es[e].v;if(belong[i] == belong[v]) continue;st1.insert(belong[i]);st2.insert(belong[v]);}}if(sccnum == 1){puts("1\n0");return 0;}cout<<sccnum - st2.size()<<endl;cout<<max(sccnum - st1.size(),sccnum - st2.size())<<endl; }
總結
以上是生活随笔為你收集整理的Network of Schools POJ - 1236 tarjan强连通分量缩点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一图看懂iQOO双11优惠 这次主打的就
- 下一篇: Summer Training day4