E. Bear and Forgotten Tree 2
题目连接:
http://www.codeforces.com/contest/653/problem/E
Description
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear. He once had a tree with n vertices but he lost it. He still remembers something about the lost tree though.
You are given m pairs of vertices (a1, b1), (a2, b2), …, (am, bm). Limak remembers that for each i there was no edge between ai and bi. He also remembers that vertex 1 was incident to exactly k edges (its degree was equal to k).
Is it possible that Limak remembers everything correctly? Check whether there exists a tree satisfying the given conditions
Input
The first line of the input contains three integers n, m and k () — the number of vertices in Limak’s tree, the number of forbidden pairs of vertices, and the degree of vertex 1, respectively.
The i-th of next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the i-th pair that is forbidden. It’s guaranteed that each pair of vertices will appear at most once in the input.
Output
Print “possible” (without quotes) if there exists at least one tree satisfying the given conditions. Otherwise, print “impossible” (without quotes).
Sample Input
5 4 2
1 2
2 3
4 2
4 1
Sample Output
possible
Hint
题意
给你n个点,然后给你m个限制,每个限制说ai,bi之间不能连边。
问你能否构造出一棵生成树,且1号点的度数恰好等于k
题解:
首先忽略掉恰好等于k这个条件,实际上就是判断这个图是否连通就好了。
然后我们看看1号点的反图的度数是否大于等于k,小于k肯定不行。
然后我们把1号点去掉,跑bfs/dfs,看有多少个连通块和1号点能够相连,如果有大于k个连通块,肯定也是不行的。
小于等于k个连通块就可以。
然后现在问题是那个bfs和dfs跑连通块复杂度可能是n^2的,你遍历边的时候,会遍历到无意义的点。
所以我们需要用一个set去维护现在有哪些点还没有访问。
总之,就是你需要实现一个类似lowbit的功能,然后就可以优化你的dfs/bfs。
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e5+5;
int n,m,k;
set<int>vis,E[maxn];
int q[maxn],st;
void solve(int x)
{
vis.erase(x);
q[st++]=x;
for(int i=0;i<st;i++)
{
int now = q[i];
int pre = 1;
while(1)
{
auto next = vis.upper_bound(pre);
if(next==vis.end())break;
int v = *next;
pre = v;
if(E[now].count(v))continue;
q[st++]=v;vis.erase(v);
}
}
}
int main()
{
scanf("%d%d%d",&n,&m,&k);
for(int i=1;i<=m;i++)
{
int x,y;scanf("%d%d",&x,&y);
E[x].insert(y);
E[y].insert(x);
}
if(k>n-1-E[1].size())return puts("impossible"),0;
for(int i=2;i<=n;i++)vis.insert(i);
int cnt=0;
for(int i=2;i<=n;i++)
{
if(vis.count(i))
{
cnt++;st=0;
solve(i);
int flag = 0;
for(int j=0;j<st;j++)if(!E[1].count(q[j]))flag=1;
if(flag==0)return puts("impossible"),0;
}
}
if(cnt>k)return puts("impossible"),0;
return puts("possible"),0;
}