jzoj2473. 【NOI2011中山聯考7.18】殺人遊戲(強連通分量)
阿新 • • 發佈:2019-01-22
2473. 【NOI2011中山聯考7.18】殺人遊戲
Description
一位冷血的殺手潛入Na-wiat,並假裝成平民。警察希望能在N個人裡面,查出誰是殺手。
警察能夠對每一個人進行查證,假如查證的物件是平民,他會告訴警察,他認識的人,誰是殺手,誰是平民。假如查證的物件是殺手,殺手將會把警察幹掉。
現在警察掌握了每一個人認識誰。
每一個人都有可能是殺手,可看作他們是殺手的概率是相同的。
問:根據最優的情況,保證警察自身安全並知道誰是殺手的概率最大是多少?
Input
輸入檔案killer.in,第一行有兩個整數N,M。
接下來有M行,每行兩個整數x,y,表示x認識y(y不一定認識x,例如胡錦濤同志)。
Output
輸出檔案killer.out僅包含一行一個實數,保留小數點後面6位,表示最大概率。
Sample Input
5 4
1 2
1 3
1 4
1 5
Sample Output
0.800000
Hint
【樣例解釋】
警察只需要查證1。假如1是殺手,警察就會被殺。假如1不是殺手,他會告訴警察2,3,4,5誰是殺手。而1是殺手的概率是0.2,所以能知道誰是殺手但沒被殺的概率是0.8。
【資料規模】
對於30%的資料有1≤N ≤ 10,0≤M ≤10
對於100%的資料有1≤N ≤ 10 0000,0≤M ≤ 30 0000
分析:顯然,這是一個有向有環圖,對於每個環只要知道其中一個人的身份即可知道所有人的身份,也就是說只需要問其中一個人,因此我們可以把環縮成一個點,得到一張有向無環圖,那麼容易發現,只要把所有入度為0的點詢問一次就可以知道所有點的身份,統計一下入度為0的點的個數ans,1-ans/n即為答案。
程式碼
#include <cstdio> #include <cstring> #include <string> #include <stack> #define N 500000 using namespace std; struct arr { int to,nxt; }a[N],c[N]; int n,m,l,ls[N],lc,lsc[N],d[N],size; int dfn[N],low[N],b[N],siz[N],tot,cnt; bool v[N],vis[N],fl; stack<int> s; double fmax(double x, double y){return x>y?x:y;} int fmin(int x, int y){return x<y?x:y;} int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') {if (ch == '-') f = -1; ch = getchar();} while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return x * f; } void add(int x, int y) { a[++l].to = y; a[l].nxt = ls[x]; ls[x] = l; } void addc(int x, int y) { c[++lc].to = y; c[lc].nxt = lsc[x]; lsc[x] = lc; } void tarjan(int x) { dfn[x] = low[x] = ++tot; s.push(x); v[x] = true; for (int i = ls[x]; i; i = a[i].nxt) if (!dfn[a[i].to]) { tarjan(a[i].to); low[x] = fmin(low[x], low[a[i].to]); } else if (v[a[i].to]) low[x] = fmin(low[x], dfn[a[i].to]); if (low[x] == dfn[x]) { ++cnt; int j; do { j = s.top(); s.pop(); siz[cnt]++; b[j] = cnt; v[j] = false; }while (x != j); } } void dfs(int x) { vis[x] = true; size += siz[x]; for (int i = lsc[x]; i; i = c[i].nxt) if (!vis[c[i].to]) dfs(c[i].to); } int main() { freopen("investigation.in","r",stdin); freopen("investigation.out","w",stdout); scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++) { int x, y; x = read(), y = read(); add(x, y); } for (int i = 1; i <= n; i++) if (!dfn[i]) tarjan(i); for (int i = 1; i <= n; i++) for (int j = ls[i]; j; j = a[j].nxt) if (b[i] != b[a[j].to]) addc(b[i],b[a[j].to]),d[b[a[j].to]]++; int ans = 0; for (int i = 1; i <= cnt; i++) if (!d[i]) { if (siz[i] == 1 && !fl) { for (int j = lsc[i]; j; j = c[j].nxt) if (d[c[j].to] != 1) fl = true; } ans++; } if (fl || ans == n) ans--; double xx = 1.0 * ans / (1.0 * n); printf("%.6lf", 1.0 - xx); fclose(stdin); fclose(stdout); }