Given an undirected, unweighted, connected graph, where each edge is colored either blue or red, determine whether a spanning tree with exactly k blue edges exists.
There will be several test cases in the input. Each test case will begin with a line with three integers:
n m k
Where n (2≤n≤1,000) is the number of nodes in the graph, m (limited by the structure of the graph) is the number of edges in the graph, and k (0≤k
c f t
Where c is a character, either capital ‘R’ or capital ‘B’, indicating the color of the edge, and f and t are integers (1≤f,t≤n, t≠f) indicating the nodes that edge goes from and to. The graph is guaranteed to be connected, and there is guaranteed to be at most one edge between any pair of nodes.
The input will end with a line with three 0s.
For each test case, output single line, containing 1 if it is possible to build a spanning tree with exactly k blue edges, and 0 if it is not possible. Output no extra spaces, and do not separate answers with blank lines.
3 3 2
B 1 2
B 2 3
R 3 1
2 1 1
R 1 2
0 0 0
1
0
题意:
很多组数据,以0、0、0结束。一组数据 给你n个点,m组边和数字k,接着给你每一组边是 c f t 代表f与t之间的颜色是c,问你是否能存在刚好是k条蓝边生成的生成树
这题是看别人的题解才知道的,意思是你先确定好最少需要几条蓝边和最多需要几条蓝边,如果数值k在这之间那么就能存在
代码:
#include
using namespace std;
int fa[1001];
struct pe{
int id,x,y;
}p[1000005];
int gen(int k){
if(k==fa[k]) return fa[k];
return fa[k]=gen(fa[k]);
}
bool cmp1(pe a,pe b){
return a.id<b.id;
}
bool cmp2(pe a,pe b){
return a.id>b.id;
}
inline int read()
{
int xx=0,ff=1;
char ch;
ch=getchar();
while(ch>'9'||ch<'0')
{
if(ch=='-') ff=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
xx=(xx<<3)+(xx<<1)+ch-'0';
ch=getchar();
}
return xx*ff;
}
int main()
{
int n,m,k;
while(scanf("%d%d%d",&n,&m,&k),n||m||k){
string s;
int x,y;
for(int i=1;i<=n;i++)fa[i]=i;
for(int t=0;t<m;t++){
cin>>s;
x=read(),y=read();
if(s=="B"){
p[t]={1,x,y};
}else{
p[t]={0,x,y};
}
}
int ans1=0,ans2=0;
sort(p,p+m,cmp1);
for(int i=0;i<m;i++){
x=gen(p[i].x),y=gen(p[i].y);
if(x!=y){
fa[x]=y;
if(p[i].id==1){
ans1++;
}
}
}
for(int i=1;i<=n;i++)fa[i]=i;
sort(p,p+m,cmp2);
for(int i=0;i<m;i++){
x=gen(p[i].x),y=gen(p[i].y);
if(x!=y){
fa[x]=y;
if(p[i].id==1){
ans2++;
}
}
}
// cout<
if(k>=ans1&&k<=ans2) printf("1\n");
else printf("0\n");
}
return 0;
}