连通性·四
好吧,这简单题敲了好久。。快一上午了,,基础不好诶。。
AC代码:
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <utility>
#include <iostream>
#include <algorithm>
#include <functional>
#define LL long long
#define INF 0x7fffffff
using namespace std;
const int maxn = 20005;
int n, m;
pair<int, int> e[100005];//用pair存边
vector<int> G[maxn];//整个图
map<pair<int, int>, int> mp;//标记每条边的分组,刚开始为0
map<pair<int, int>, int> id;//记录每条边的编号
int vis[maxn];
int dfn[maxn];
int low[maxn];
stack<pair<int, int> > s;
int cur_time, cnt;
void dfs(int u, int fa) {
dfn[u] = low[u] = ++ cur_time;
vis[u] = 1;
int child = 0;
int d = G[u].size();
for(int i = 0; i < d; i ++) {
int v = G[u][i];
pair<int, int> pai = make_pair(min(u, v), max(u, v));
if(mp[pai] != 0) continue;
if(!vis[v]) {
child ++;
s.push(pai);
dfs(v, u);
low[u] = min(low[u], low[v]);
if(fa == -1 && child > 1) {//求出树根为割点的时候的点的双连通分量
cnt ++;
stack<pair<int, int> > ss;
int MIN = INF;
while(s.top() != pai) {
MIN = min(MIN, id[s.top()]);
ss.push(s.top());
s.pop();
}
MIN = min(MIN, id[pai]);
ss.push(pai);
s.pop();
//cout << MIN << " haha";
while(!ss.empty()) {
mp[ss.top()] = MIN;
ss.pop();
}
}
if(fa != -1 && low[v] >= dfn[u]) {//求出树根以外的结点为割点的点的双连通分量
//cout << "low " << low[v] << " dfn " << dfn[u] << endl;
cnt ++;
stack<pair<int, int> > ss;
int MIN = INF;
while(s.top() != pai) {
MIN = min(MIN, id[s.top()]);
//cout << id[s.top()] << " " << s.top().first << " " << s.top().second << endl;
ss.push(s.top());
s.pop();
}
//cout << id[pai] << endl;
MIN = min(MIN, id[pai]);
ss.push(pai);
s.pop();
//cout << MIN << " haha" << endl;
while(!ss.empty()) {
mp[ss.top()] = MIN;
ss.pop();
}
}
}
else if(v != fa) {//反向边的情况
s.push(pai);
low[u] = min(low[u], dfn[v]);
}
}
}
int main() {
scanf("%d %d", &n, &m);
for(int i = 1; i <= m; i ++) {
scanf("%d %d", &e[i].first, &e[i].second);
G[e[i].first].push_back(e[i].second);
G[e[i].second].push_back(e[i].first);
mp[e[i]] = 0;
id[e[i]] = i;
}
cur_time = cnt = 0;
dfs(1, -1);
//求剩余那部分的点的双连通分量
stack<pair<int, int> > ss;
int MIN = INF;
while(!s.empty()) {
ss.push(s.top());
MIN = min(MIN, id[s.top()]);
s.pop();
}
if(MIN != INF) cnt ++;
while(!ss.empty()) {
mp[ss.top()] = MIN;
ss.pop();
}
printf("%d\n", cnt);
for(int i = 1; i < m; i ++) {
printf("%d ", mp[e[i]]);
}
printf("%d\n", mp[e[m]]);
return 0;
}