大意:让你求无向图的桥(割边)
思路:一次查询,重建一次图,然后求一次割边,TLE。去网上开了看资料,可以用LCA暴力查询,唔,改天看看LCA。
TLE CODE:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define MAXN 100010
#define MAXM 500010
struct Edge
{
int v, next;
}edge[MAXM];
int first[MAXN], low[MAXN], dfn[MAXN];
int n, m;
int cnt;
int scnt, top, tot;
int nbridge;
void init1()
{
cnt = 0;
for(int i = 1; i <= n; i++) first[i] = -1;
}
void init2()
{
scnt = top = tot = nbridge = 0;
for(int i = 1; i <= n; i++) dfn[i] = 0;
}
void read_graph(int u, int v)
{
edge[cnt].v = v;
edge[cnt].next = first[u], first[u] = cnt++;
}
void Tarjan(int u, int fa)
{
int v;
low[u] = dfn[u] = ++tot;
bool repeat = 0;
for(int e = first[u]; e != -1; e = edge[e].next)
{
v = edge[e].v;
if(v == fa && !repeat)
{
repeat = 1;
continue;
}
if(!dfn[v])
{
Tarjan(v, u);
low[u] = min(low[u], low[v]);
if(dfn[u] < low[v]) nbridge++;
}
low[u] = min(low[u], dfn[v]);
}
}
void solve()
{
init2();
Tarjan(1, -1);
printf("%d\n", nbridge);
}
int main()
{
int times = 0;
while(scanf("%d%d", &n, &m) && (n || m))
{
init1();
while(m--)
{
int u, v;
scanf("%d%d", &u, &v);
read_graph(u, v);
read_graph(v, u);
}
int Q;
scanf("%d", &Q);
printf("Case %d:\n", ++times);
while(Q--)
{
int u, v;
scanf("%d%d", &u, &v);
read_graph(u, v);
read_graph(v, u);
solve();
}
printf("\n");
}
return 0;
}
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define MAXN 100010
#define MAXM 500010
struct Edge
{
int v, next;
}edge[MAXM];
int first[MAXN], low[MAXN], dfn[MAXN];
int n, m;
int cnt;
int scnt, top, tot;
int nbridge;
void init1()
{
cnt = 0;
for(int i = 1; i <= n; i++) first[i] = -1;
}
void init2()
{
scnt = top = tot = nbridge = 0;
for(int i = 1; i <= n; i++) dfn[i] = 0;
}
void read_graph(int u, int v)
{
edge[cnt].v = v;
edge[cnt].next = first[u], first[u] = cnt++;
}
void Tarjan(int u, int fa)
{
int v;
low[u] = dfn[u] = ++tot;
bool repeat = 0;
for(int e = first[u]; e != -1; e = edge[e].next)
{
v = edge[e].v;
if(v == fa && !repeat)
{
repeat = 1;
continue;
}
if(!dfn[v])
{
Tarjan(v, u);
low[u] = min(low[u], low[v]);
if(dfn[u] < low[v]) nbridge++;
}
low[u] = min(low[u], dfn[v]);
}
}
void solve()
{
init2();
Tarjan(1, -1);
printf("%d\n", nbridge);
}
int main()
{
int times = 0;
while(scanf("%d%d", &n, &m) && (n || m))
{
init1();
while(m--)
{
int u, v;
scanf("%d%d", &u, &v);
read_graph(u, v);
read_graph(v, u);
}
int Q;
scanf("%d", &Q);
printf("Case %d:\n", ++times);
while(Q--)
{
int u, v;
scanf("%d%d", &u, &v);
read_graph(u, v);
read_graph(v, u);
solve();
}
printf("\n");
}
return 0;
}