HYSBZOJ 2337 [HNOI2011]XOR和路徑
題目大意
分析
我們先考慮將這個問題轉化爲一個期望 DP ,設爲從走到的異或和的期望值,並記節點的度數爲,之間的邊權爲。
則可以與它鄰接的節點轉移過來,所以不難得出:
然而這個圖裏面有自環、重邊等,這個方程是有後效性的。
我們發現總點數非常小,所以我們可以考慮高斯消元來求解這個方程。
但如果用高斯消元來做的話,異或實在是不好處理。但是我們可以將數按照二進制位拆開來做。
由於期望的線性性(),異或運算每位都互不影響,那麼這樣做顯然是對的。
則重新設從到的路徑上二進制第位上爲的概率(也就是該位上爲的期望),表示邊的邊權上二進制的第位。
那麼就可以列出如下式子:
簡單整理一下:
這樣就可以用高斯消元做了。
我們對於二進制下的每一位都這樣來一遍,最終的答案就是。
總時間複雜度爲。
參考代碼
#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int Maxn = 100;
const int Maxm = 10000;
const double EPS = 1e-7;
struct Edge {
int to, dis;
Edge *nxt;
};
Edge pool[Maxm * 2 + 5];
Edge *G[Maxn + 5], *ecnt = &pool[0];
void addedge(int u, int v, int dis) {
Edge *p = ++ecnt;
p->to = v, p->dis = dis;
p->nxt = G[u], G[u] = p;
}
int N, M;
int deg[Maxn + 5];
double g[Maxn + 5][Maxn + 5];
void Gauss() {
for(int i = 1; i <= N; i++) {
int to = i;
for(; to <= N; to++)
if(fabs(g[to][i]) > EPS) break;
if(to > N) continue;
if(to != i)
for(int j = 1; j <= N + 1; j++) swap(g[to][j], g[i][j]);
double t = g[i][i];
for(int j = 1; j <= N + 1; j++) g[i][j] /= t;
for(int j = 1; j <= N; j++)
if(j != i) {
t = g[j][i];
for(int k = 1; k <= N + 1; k++)
g[j][k] -= t * g[i][k];
}
}
}
int main() {
#ifdef LOACL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
scanf("%d %d", &N, &M);
for(int i = 1; i <= M; i++) {
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
addedge(u, v, w), ++deg[u];
if(u != v) addedge(v, u, w), ++deg[v];
}
double ans = 0;
for(int k = 30; k >= 0; k--) {
memset(g, 0, sizeof g);
for(int u = 1; u < N; u++) {
g[u][u] = -deg[u];
for(Edge *p = G[u]; p != NULL; p = p->nxt) {
int v = p->to, w = (p->dis >> k) & 1;
if(w) g[u][v]--, g[u][N + 1]--;
else g[u][v]++;
}
}
g[N][N] = 1;
Gauss();
ans += (1 << k) * g[1][N + 1];
}
printf("%.3f", ans);
return 0;
}