HDU4460-Friend Chains-BFS+bitset优化

bfs的时候用bitset优化一下。

水题

 #include <cstdio>
#include <cstring>
#include <algorithm>
#include <bitset>
#include <queue>
#include <unordered_map> using namespace std; const int maxn = 1e3+;
int N,M;
unordered_map<string,int> mp; bitset<maxn> G[maxn];
bitset <maxn> to,unvis;
queue <int> Q; int dis[maxn];
int bfs(int rt)
{
while(!Q.empty()) Q.pop();
Q.push(rt);
dis[rt] = ; unvis.reset();
for(int i=;i<=N;i++) unvis.set(i);
int res = ;
unvis.reset(rt); while(!Q.empty())
{
int u = Q.front();
Q.pop();
to = unvis & G[u];
for(int v = to._Find_first(); v<=N; v = to._Find_next(v))
{
Q.push(v);
unvis.reset(v);
dis[v] = dis[u]+;
res = max(res,dis[v]);
}
}
//printf("")
if(unvis.any()) return -;
return res;
} int main()
{
while(scanf("%d",&N) && N)
{
mp.clear();
for(int i=;i<maxn;i++) G[i].reset();
for(int i=;i<=N;i++)
{
char tmp[];
scanf("%s",tmp);
mp[tmp] = i;
}
scanf("%d",&M);
for(int i=;i<M;i++)
{
char tmp1[],tmp2[];
scanf("%s %s",tmp1,tmp2);
int u = mp[tmp1],v = mp[tmp2];
//printf("add edge:%d %d\n",u,v);
G[u].set(v);G[v].set(u);
} int ans = ;
bool unconnected = ;
for(int i=;i<=N;i++)
{
int res = bfs(i);
if(res == -){unconnected = true;break;}
ans = max(ans,res);
}
if(unconnected) printf("-1\n");
else printf("%d\n",ans);
}
}
上一篇:hdu_5036_Explosion(bitset优化传递闭包)


下一篇:华为ensp使用