Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 125536/65536 K (Java/Others) Total Submission(s): 4087 Accepted Submission(s): 1056 Problem Description Social Network is popular these days.The Network helps us know about those guys who we are following intensely and makes us keep up our pace with the trend of modern times. Input The input is a relation description map. Output In the first line,output an integer n,represents the number of key relations in the relation description map. Sample Input 1 4 4 saerdna aswmtjdsj aswmtjdsj mabodx mabodx biribiri aswmtjdsj biribiri Sample Output 1 saerdna aswmtjdsj Source 2011 Invitational Contest Host by BUPT Recommend chenyongfu |
题目大意:现在有n个名字,m个这些名字之间的联通,问你他们中的桥是哪一对,输出时要按照给出的一对的先后输出
思路:直接用tarjan算法判断是否是桥,还有可能这个图根本不是联通的,还要判断一下连通性,因为输出的限制,在这里我是写的先判断并标记,后输出的模式,字符的话直接用map存储即可,
代码:
#include<cstdio>
#include<cstring>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
const int maxn=10000+10;
const int maxm=100000+10;
int n,m;
struct node
{
char s[20];
bool operator <(const node& rhs)const
{
return strcmp(s,rhs.s)<0;
}
};
map<node,int> mp;//将字符串node映射成节点编号
struct Edge
{
node u,v;
bool flag;//标记该边是不是桥
}e[maxm];
vector<int> G[maxn];
int pre[maxn],low[maxn];
int dfs_clock;
void tarjan(int u,int fa)
{
low[u]=pre[u]=++dfs_clock;
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i];
if(v==fa) continue;
if(!pre[v])
{
tarjan(v,u);
low[u]=min(low[u],low[v]);
}
else low[u] = min(low[u],pre[v]);
}
}
int main()
{
int t;scanf("%d",&t);
while(t--)
{
int id=0;
scanf("%d%d",&n,&m);
mp.clear();
dfs_clock=0;
memset(pre,0,sizeof(pre));
for(int i=1;i<=n;i++) G[i].clear();
for(int i=0;i<m;i++)
{
e[i].flag=false;
scanf("%s%s",e[i].u.s,e[i].v.s);
if(mp.find(e[i].u)==mp.end()) mp[e[i].u]= ++id;
if(mp.find(e[i].v)==mp.end()) mp[e[i].v]= ++id;
int x = mp[e[i].u], y=mp[e[i].v];
G[x].push_back(y);
G[y].push_back(x);
}
tarjan(1,-1);
bool ok=true;//判断是否连通图
for(int i=1;i<=n;i++)if(!pre[i])
{
ok=false;
break;
}
if(!ok) printf("0\n");
else
{
int ans=0;
for(int i=0;i<m;i++)
{
int u=mp[e[i].u], v=mp[e[i].v];
if(low[u]>pre[v]||low[v]>pre[u]) e[i].flag=true,ans++;
}
printf("%d\n",ans);
for(int i=0;i<m;i++)if(e[i].flag)
printf("%s %s\n",e[i].u.s,e[i].v.s);
}
}
}