Berland and the Shortest Paths CodeForces - 1005F(最短路樹)
阿新 • • 發佈:2018-09-13
pac mes ber lan short nbsp ont fin ini
最短路樹就是用bfs走一遍就可以了 d[v] = d[u] + 1 表示v是u的前驅邊
然後遍歷每個結點 存下它的前驅邊 再用dfs遍歷每個結點 依次取每個結點的某個前驅邊即可
#include <bits/stdc++.h> #define mem(a, b) memset(a, b, sizeof(a)) using namespace std; const int maxn = 1e6+10, INF = 0x7fffffff; int n, m, k, cnt; int head[maxn], d[maxn]; vector<int> f[maxn]; vector<string> g; char str[maxn]; struct node { int u, v, next; }Node[maxn<<1]; void add_(int u, int v) { Node[cnt].u = u; Node[cnt].v = v; Node[cnt].next = head[u]; head[u] = cnt++; } void add(int u, int v) { add_(u, v); add_(v, u); } void init() { mem(head,-1); cnt = 0; } void dfs(int u) { if(g.size() >= k) return; if(u == n+1) { g.push_back(str); return; } //cout<< 111 <<endl; for(int i=0; i<f[u].size(); i++) { str[f[u][i]/2] = ‘1‘; // cout<< str <<endl; dfs(u+1); str[f[u][i]/2] = ‘0‘; } } void bfs(int u) { mem(d, -1); queue<int> Q; Q.push(u); d[u] = 0; while(!Q.empty()) { int u = Q.front(); Q.pop(); for(int i=head[u]; i!=-1; i=Node[i].next) { node e = Node[i]; if(d[e.v] == -1) { d[e.v] = d[u] + 1; Q.push(e.v); } } } } int main() { init(); int u, v; cin>> n >> m >> k; for(int i=0; i<m; i++) { cin>> u >> v; add(u, v); } bfs(1); // cout<< 11 <<endl; for(int i=1; i<=n; i++) { for(int j=head[i]; j!=-1; j=Node[j].next) if(d[Node[j].v] + 1 == d[i]) { f[i].push_back(j); // cout<< i << " " << j/2 <<endl; } } for(int i=0; i<m; i++) str[i] = ‘0‘; dfs(2); cout<< g.size() <<endl; for(int i=0; i<g.size(); i++) { cout<< g[i] <<endl; } return 0; }
Berland and the Shortest Paths CodeForces - 1005F(最短路樹)