根据关系构图:相似的两本书之间有一条双向边。然后利用dfs找出每个连通块,除了这个连通块中耗时最小的一本书要用原来的时间读完,其他的书只要一半时间就可以读完,直到全部连通块处理完便可找到答案。
搜索永远是那么得迷人。。。。
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include
<
iostream
>
#include < cstring >
#include < vector >
using namespace std;
const int MAX = 105 ;
vector < int > vec[MAX];
int n,m,tim[MAX],_min,temp[MAX],len,root;
bool vis[MAX];
void dfs( int k) // dfs找连通块
{
/* 找耗时最小的书本 */
if (tim[k] < _min) {_min = tim[k]; root = k;}
temp[len ++ ] = k; vis[k] = true ;
for ( int i = 0 ;i < vec[k].size(); ++ i)
{
if ( ! vis[vec[k][i]]) dfs(vec[k][i]);
}
}
int main()
{
int i,u,v;
while (cin >> n >> m)
{
if (n == 0 && m == 0 ) break ;
for (i = 0 ;i < n; ++ i) cin >> tim[i];
for (i = 0 ;i < m; ++ i)
{
cin >> u >> v;
vec[u].push_back(v);
vec[v].push_back(u);
}
memset(vis, false , sizeof (vis));
int sum = 0 ;
for (i = 0 ;i < n; ++ i)
{
if ( ! vis[i]) {
_min = 2000000000 ; len = 0 ;
dfs(i);
sum += tim[root];
for ( int j = 0 ;j < len; ++ j)
{
if (temp[j] != root)
sum = sum + tim[temp[j]] / 2 ;
}
}
}
cout << sum << endl;
for (i = 0 ;i < n; ++ i) vec[i].clear();
}
return 0 ;
}
#include < cstring >
#include < vector >
using namespace std;
const int MAX = 105 ;
vector < int > vec[MAX];
int n,m,tim[MAX],_min,temp[MAX],len,root;
bool vis[MAX];
void dfs( int k) // dfs找连通块
{
/* 找耗时最小的书本 */
if (tim[k] < _min) {_min = tim[k]; root = k;}
temp[len ++ ] = k; vis[k] = true ;
for ( int i = 0 ;i < vec[k].size(); ++ i)
{
if ( ! vis[vec[k][i]]) dfs(vec[k][i]);
}
}
int main()
{
int i,u,v;
while (cin >> n >> m)
{
if (n == 0 && m == 0 ) break ;
for (i = 0 ;i < n; ++ i) cin >> tim[i];
for (i = 0 ;i < m; ++ i)
{
cin >> u >> v;
vec[u].push_back(v);
vec[v].push_back(u);
}
memset(vis, false , sizeof (vis));
int sum = 0 ;
for (i = 0 ;i < n; ++ i)
{
if ( ! vis[i]) {
_min = 2000000000 ; len = 0 ;
dfs(i);
sum += tim[root];
for ( int j = 0 ;j < len; ++ j)
{
if (temp[j] != root)
sum = sum + tim[temp[j]] / 2 ;
}
}
}
cout << sum << endl;
for (i = 0 ;i < n; ++ i) vec[i].clear();
}
return 0 ;
}