Jack's socks--HOJ 11903

1、题目类型:图论。

2、解题思路:(1)根据输入建立图的vector邻接表;(2)vector连接表中寻找度为 1 的点,并其连接点一起标示为同一双sock,直到vector中所有顶点全部标示,否则输出'NO';(3)对所有成双的sock按照其标号小的进行排序,并依次输出。

3、注意事项:注意题意理解,题中说说的是将所有成双的sock按序输出,而不是单个输出其最小的两双。

4、实现方法:

  
    
#include < iostream >
#include
< vector >
#include
< queue >
#include
< algorithm >
using namespace std;
#define MyMax 1001

struct Pair
{
int one,two;
};

int n,m;
vector
< int > head[MyMax];
vector
< Pair > V;

int cmp(Pair A,Pair B)
{
return A.one < B.one;
}

void Solve()
{
queue
< int > Q;
int i,j,k,w,cnt = 0 ,flag = 1 ;
int vis[MyMax] = { 0 };
vector
< int > ::iterator it;
Pair P;
while (flag)
{
flag
= 0 ;
for (i = 1 ;i <= n;i ++ )
{
if (head[i].size() == 1 )
{
cnt
++ ;
int v = head[i][ 0 ];
head[i].clear();
for (j = 0 ;j < head[v].size();j ++ )
{
int u = head[v][j];
if ((it = find(head[u].begin(),head[u].end(),v)) != head[u].end())
{
head[u].erase(it);
}
}
head[v].clear();
if (i > v)
{
P.one
= v;
P.two
= i;
}
else
{
P.one
= i;
P.two
= v;
}
V.push_back(P);
flag
= 1 ;
break ;
}
}
}
if (cnt == n / 2 )
{
cout
<< " YES " << endl;
sort(V.begin(),V.end(),cmp);
for (i = 0 ;i < V.size();i ++ )
cout
<< V[i].one << " " << V[i].two << endl;
}
else
cout
<< " NO " << endl;
}

int main()
{
int i,T,a,b;
cin
>> T;
while (T -- )
{
cin
>> n >> m;
for (i = 1 ;i <= n;i ++ )
head[i].clear();
V.clear();
for (i = 0 ;i < m;i ++ )
{
scanf(
" %d %d " , & a, & b);
head[b].push_back(a);
head[a].push_back(b);
}
Solve();
}
return 0 ;
}

 

你可能感兴趣的:(SOC)