题目
描述 Description
strork 让他的N (1 <= N <= 250)只编号为从1到N的奶牛在田地里玩.这些奶牛决定用M条(1<=M<=N*(N+1)/2)牛绳将各自连接起来.当然,不会出现一对牛被两条及以上牛绳连接起来.输入告诉你每一条牛绳连接的两只奶牛C1和C2(1 <= c1 <= N; 1 <= c2 <= N; c1 <> c2).
strork要求奶牛们与1号奶牛相连.现在你要帮助strork找出所有没有与1号奶牛相连的奶牛.这里的相连既可以是直接的,也可以是间接的(特别的,1号奶牛总是与自己相连).将没有与1号奶牛相连的奶牛的编号升序输出.如果你找不到这样的一只牛,那么就输出0.
解释一下的话,看这个有6只奶牛和4个连接的例子:
1----2 4—5
\ |
\ | 6
\ |
3
很明显,4,5,6号牛没有同1号牛相连.
输入格式 Input Format
第1行:两个用空格分开的整数N,M
第2…M+1行:每一行有两个整数.第i+1行描述的是绳子i连接的两只奶牛的编号,即C1和C2.
输出格式 Output Format
很多行:每一行包含一个整数,意义如题目所说.升序输出.
样例输入 Sample Input
6 4
1 3
2 3
1 2
4 5
样例输出 Sample Output
4
5
6
时间限制 Time Limitation
1s
来源 Source
usaco 月赛 daisy 10 nov
题解
1.用邻接矩阵存储图,
2.再用传递闭包判断是否能走到这个点,
3.最后,判断一下各店与一号点是否连接,连接则输出,否则不输出。
代码
#include<bits/stdc++.h>
using namespace std;
const int maxnum=3010;
bool flag=true;
int a[maxnum][maxnum],n,m;
inline int read()
{
int f=1,num=0;
char ch=getchar();
while (ch<'0'||ch>'9') { if (ch=='-') f=-1; ch=getchar(); }
while (ch>='0'&&ch<='9') { num=(num<<1)+(num<<3)+ch-'0'; ch=getchar(); }
return num*f;
}
int main()
{
n=read(),m=read();
for (int i=1;i<=n;i++)
a[i][i]=0;
for (int i=1;i<=m;i++)
{
int x=read(),y=read();
a[x][y]=1,a[y][x]=1;
}
for (int k=1;k<=n;k++)
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++)
if (a[i][k]&&a[k][j])
a[i][j]=1;
for (int i=2;i<=n;i++)
if ((!a[1][i])||(!a[i][1]))
{
cout<<i<<endl;
flag=false;
}
if (flag==true) cout<<0<<endl;
return 0;
}
小结
这算是一道图论入门题,。。。。。。。。。。。。。。。。。。