ZJFC-1239
这是一道省赛题目 解法是构造概率矩阵A 根据要进行的次数n 使用二分法计算转移矩阵(A)^n 再使用转移公式res=init*(A)^n
可以很快计算出最终答案
1
#include <iostream>
2
using namespace std;
3
double hash[30];
4
double mm[30];
5
double matrix[30][30];
6
double temp[30][30];
7
long N;
8
void Mulity(double m1[][30] ,double m2[][30])
9
{
10
long i,j,k;
11
double tt[30][30];
12
memset(tt,0,sizeof(tt));
13
14
for (i=1;i<=N;++i)
15
{
16
for (j=1;j<=N;++j)
17
{
18
double t=0;
19
for (k=1;k<=N;++k)
20
{
21
t+=m1[i][k]*m2[k][j];
22
}
23
tt[i][j]=t;
24
}
25
}
26
27
memcpy(m1,tt,sizeof(tt));
28
};
29
30
31
int main()
32
{
33
long T;
34
scanf("%ld",&T);
35
while (T--)
36
{
37
memset(matrix,0,sizeof(matrix));
38
scanf("%ld",&N);
39
long i,k;
40
for (i=1;i<=N;++i)
41
{
42
scanf("%lf",&hash[i]);
43
}
44
45
for (i=1;i<=N;++i)
46
{
47
long t;
48
scanf("%ld",&t);
49
double rate=1.0/t;
50
while (t--)
51
{
52
long other;
53
scanf("%ld",&other);
54
matrix[i][other]=rate;
55
}
56
}
57
58
long n;
59
scanf("%ld",&n);
60
61
62
long p=n;
63
64
memset(temp,0,sizeof(temp));
65
66
for (i=1;i<30;++i)
67
{
68
temp[i][i]=1;
69
}
70
71
72
while (p>1)
73
{
74
if (p%2!=0)
75
{
76
Mulity(temp,matrix);
77
}
78
79
Mulity(matrix,matrix);
80
p/=2;
81
}
82
83
Mulity(matrix,temp);
84
memset(mm,0,sizeof(mm));
85
86
for (i=1;i<=N;++i)
87
{
88
double t=0;
89
for (k=1;k<=N;++k)
90
{
91
t+=hash[k]*matrix[k][i];
92
}
93
mm[i]=t;
94
}
95
96
memcpy(hash,mm,sizeof(mm));
97
98
for (i=1;i<=N;++i)
99
{
100
if (i!=1)
101
{
102
printf(" ");
103
}
104
printf("%.2lf",hash[i]);
105
}
106
printf("\n");
107
108
}
109
return 0;
110
}
#include <iostream>2
using namespace std;3
double hash[30];4
double mm[30];5
double matrix[30][30];6
double temp[30][30];7
long N;8
void Mulity(double m1[][30] ,double m2[][30])9
{10
long i,j,k;11
double tt[30][30];12
memset(tt,0,sizeof(tt));13

14
for (i=1;i<=N;++i)15
{16
for (j=1;j<=N;++j)17
{18
double t=0;19
for (k=1;k<=N;++k)20
{21
t+=m1[i][k]*m2[k][j];22
}23
tt[i][j]=t;24
}25
}26

27
memcpy(m1,tt,sizeof(tt));28
};29

30

31
int main()32
{33
long T;34
scanf("%ld",&T);35
while (T--)36
{37
memset(matrix,0,sizeof(matrix));38
scanf("%ld",&N);39
long i,k;40
for (i=1;i<=N;++i)41
{42
scanf("%lf",&hash[i]);43
}44

45
for (i=1;i<=N;++i)46
{47
long t;48
scanf("%ld",&t);49
double rate=1.0/t;50
while (t--)51
{52
long other;53
scanf("%ld",&other);54
matrix[i][other]=rate;55
}56
}57

58
long n;59
scanf("%ld",&n);60

61

62
long p=n;63
64
memset(temp,0,sizeof(temp));65

66
for (i=1;i<30;++i)67
{68
temp[i][i]=1;69
}70

71

72
while (p>1)73
{74
if (p%2!=0)75
{76
Mulity(temp,matrix);77
}78

79
Mulity(matrix,matrix);80
p/=2;81
}82

83
Mulity(matrix,temp);84
memset(mm,0,sizeof(mm));85

86
for (i=1;i<=N;++i)87
{88
double t=0;89
for (k=1;k<=N;++k)90
{91
t+=hash[k]*matrix[k][i];92
}93
mm[i]=t;94
}95

96
memcpy(hash,mm,sizeof(mm));97

98
for (i=1;i<=N;++i)99
{100
if (i!=1)101
{102
printf(" ");103
}104
printf("%.2lf",hash[i]);105
}106
printf("\n");107

108
}109
return 0;110
}



浙公网安备 33010602011771号