(有任何问题欢迎留言或私聊 && 欢迎交流讨论哦
Catalog
Problem:传送门 cf118E
原题目描述在最下面。
使无向图定向后的有向图强连通。
Solution:
对无向图跑一遍tarjan就行了。无向图建双向边,选择每条边第一次经过的方向即可。
若有桥或者不连通则无解。
AC_Code:
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
const int MXN = 1e6 + 5;
const int MXE = 2e6 + 6;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
int n, m;
struct lp{
int v, nex, id;
}cw[MXE];
int head[MXN], tot;
int dfn[MXN], low[MXN], vis[MXE], inde, bridge;
int qltNum, inStack[MXN];
int stak[MXE], top;
int ans[MXE];
void add_edge(int u,int v,int i) {
cw[++tot].v = v; cw[tot].nex = head[u]; cw[tot].id = i;
head[u] = tot;
cw[++tot].v = u; cw[tot].nex = head[v]; cw[tot].id = i;
head[v] = tot;
}
void dfs_tj(int u,int ba) {
dfn[u] = low[u] = ++inde;
inStack[u] = 1;
stak[++top] = u;
for(int i = head[u]; ~i; i = cw[i].nex) {
int v = cw[i].v;
if(vis[i]) continue;
vis[i] = vis[i^1] = 1;
if(!dfn[v]) {
dfs_tj(v, u);
low[u] = min(low[u], low[v]);
if(low[v] > dfn[u]) {
bridge = 1;
}
}else if(inStack[v] == 1) {
low[u] = min(low[u], dfn[v]);
}
ans[cw[i].id] = !(i % 2);
}
if(dfn[u] == low[u]) {
int v;
++ qltNum;
do{
v = stak[top--];
inStack[v] = 2;
}while(u != v);
}
}
int main(int argc, char const *argv[]) {
scanf("%d%d", &n, &m);
tot = -1; inde = top = qltNum = bridge = 0;
for(int i = 1; i <= n; ++i) head[i] = -1;
for(int i = 0, a, b; i < m; ++i) {
scanf("%d%d", &a, &b);
add_edge(a, b, i);
}
dfs_tj(1, -1);
for(int i = 1; i <= n; ++i) if(!dfn[i]) bridge = 1;
if(bridge) {
printf("impossible\n");
}else {
for(int i = 0; i < m; ++i) printf("%d", ans[i]);
printf("\n");
}
return 0;
}
Problem Description: