Explosion
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 811 Accepted Submission(s): 273
Problem Description
Everyone knows Matt enjoys playing games very much. Now, he is playing such a game. There are N rooms, each with one door. There are some keys(could be none) in each room corresponding to some doors among these N doors. Every key can open only one door. Matt has some bombs, each of which can destroy a door. He will uniformly choose a door that can not be opened with the keys in his hand to destroy when there are no doors that can be opened with keys in his hand. Now, he wants to ask you, what is the expected number of bombs he will use to open or destroy all the doors. Rooms are numbered from 1 to N.
Input
The first line of the input contains an integer T, denoting the number of testcases. Then T test cases follow.
In the first line of each test case, there is an integer N (N<=1000) indicating the number of rooms.
The following N lines corresponde to the rooms from 1 to N. Each line begins with an integer k (0<=k<=N) indicating the number of keys behind the door. Then k integers follow corresponding to the rooms these keys can open.
In the first line of each test case, there is an integer N (N<=1000) indicating the number of rooms.
The following N lines corresponde to the rooms from 1 to N. Each line begins with an integer k (0<=k<=N) indicating the number of keys behind the door. Then k integers follow corresponding to the rooms these keys can open.
Output
For each test case, output one line "Case #x: y", where x is the case number (starting from 1), y is the answer which should be rounded to 5 decimal places.
Sample Input
2 3 1 2 1 3 1 1 3 0 0 0
Sample Output
Case #1: 1.00000 Case #2: 3.00000
题目大意:
有n扇门,每次可以炸开一道门,并获得这扇门里的钥匙,求炸开门的期望。
解题思路:
其实这题就是给定一个有向图,门与对应钥匙的门之间形成有向边,每次操作随机选取一个点,然后删除这个
点和这个点能到达的点。求操作的期望。
由于一个节点可以被它自己和它的父节点删除,假如有k个这样的节点,则用这个节点来删除这个节点的概率
是1/k,对操作的期望的贡献是1*(1/k),于是只需要对每个节点,求出它的k值,k值的倒数相加即可得操作的期望。
k值怎么求,用flody算法求会超时,联通与不连通只有两个值,可以用二进制表示,i可以到达j,则i可以到达所
有j可以到达的点,满足按位或的性质,于是就可以用bitset来优化。bitset的位运算效率比直接用数组模拟效
高。
接着反向查询就可求出k值。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <bitset>
#include <algorithm>
using namespace std;
const int maxn=1010;
bitset<maxn> a[maxn];
int main()
{
int t,ca=1;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
int k;
scanf("%d",&k);
a[i].reset();
a[i][i]=1;
for(int j=0;j<k;j++)//正向建图
{
int v;
scanf("%d",&v);
a[i][v-1]=1;
}
}
for(int i=0;i<n;i++)//求所有的连通情况
{
for(int j=0;j<n;j++)
{
if(a[j][i])//j->i连通,则所有与i连通的就与j连通
a[j]|=a[i];
}
}
double ans=0;
for(int i=0;i<n;i++)
{
int cou=0;
for(int j=0;j<n;j++)//反向统计,统计所有可以到i点的点
{
if(a[j][i])
cou++;
}
ans=ans+1.0/(cou*1.0);
}
printf("Case #%d: %.5f\n",ca++,ans);
}
return 0;
}