#include <stdio.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
#include <vector>
#include <set>
typedef struct node {
int data;
int belongtotreenum;
}node;
const int maxn = 10001;
node a[maxn];
bool cmp(vector<vector<int> > a, vector<vector<int> > b)
{
return a[0][0] < b[0][0];
}
int pathNum(vector<vector<int> > path)
{
int num = 0;
for (int k = 0; k < path.size(); k++)
{
int temp = 0;
for (int j = 0; j < path[k].size(); j++)
{
temp = temp * 10 + a[path[k][j]].data;
}
num += temp;
}
//printf("%d ", num);
return num;
}
int main()
{
vector<vector<int> > path;
vector<vector<int> > forest[maxn];
int pos = -1;
int n,m;
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
int begin,end;
bool flag[maxn] = { false };
for (int i = 0; i < m; i++)
{
scanf("%d %d", &begin, &end);
if (flag[begin] == true)
{
int q = a[begin].belongtotreenum;
int pathNum = forest[q].size();
for (int k = 0; k < pathNum&&flag[end] == false; k++)
{
for (int j = 0; j < forest[q][k].size(); j++)
{
if (forest[q][k][j] == begin)
{
if (j == forest[q][k].size() - 1)
forest[q][k].push_back(end);
else
{
vector<int> newpath;
for (int i = 0; i <= j; i++)
newpath.push_back(forest[q][k][i]);
newpath.push_back(end);
forest[q].push_back(newpath);
}
flag[end] = true;
break;
}
}
}
}
else if (flag[begin] == false)
{
pos++;
vector<int> newpath;
newpath.push_back(begin);
newpath.push_back(end);
forest[pos].push_back(newpath);
flag[begin] = true;
flag[end] = true;
a[begin].belongtotreenum = pos;
a[end].belongtotreenum = pos;
}
}
for (int i = 0; i < n; i++)
{
if (flag[i] == false)
{
vector<int> newpath;
newpath.push_back(begin);
forest[++pos].push_back(newpath);
}
}
printf("%d\n", n - m);
sort(forest, forest + pos + 1, cmp);
for (int i = 0; i < pos;i++)
{
printf("%d ", pathNum(forest[i]));
}
printf("%d\n", pathNum(forest[pos]));
return 0;
}
浙大PAT 宇宙树(有瑕疵)
最新推荐文章于 2023-09-22 22:18:12 发布