贪心。。。。
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 6647 | Accepted: 2249 |
Description
Bob intends to color all the nodes of a tree with a pen. A tree has N nodes, these nodes are numbered 1, 2, ..., N. Suppose coloring a node takes 1 unit of time, and after finishing coloring one node, he is allowed to color another. Additionally, he is allowed to color a node only when its father node has been colored. Obviously, Bob is only allowed to color the root in the first try.
Each node has a "coloring cost factor", Ci. The coloring cost of each node depends both on Ci and the time at which Bob finishes the coloring of this node. At the beginning, the time is set to 0. If the finishing time of coloring node i is Fi, then the coloring cost of node i is Ci * Fi.
For example, a tree with five nodes is shown in Figure-1. The coloring cost factors of each node are 1, 2, 1, 2 and 4. Bob can color the tree in the order 1, 3, 5, 2, 4, with the minimum total coloring cost of 33.
Given a tree and the coloring cost factor of each node, please help Bob to find the minimum possible total coloring cost for coloring all the nodes.
Input
A test case of N = 0 and R = 0 indicates the end of input, and should not be processed.
Output
Sample Input
5 1
1 2 1 2 4
1 2
1 3
2 4
3 5
0 0
Sample Output
33
Source
贪心原则应该是Ci大的尽量先染色,但是由于父节点染了才能染子节点的限制使得问题不好解决了,但是Ci大的一定是在其父节点染色后立即被染色,这时大牛们的思路我也没有看明白如何证明的,但仔细一想就明白了。于是我们根据这个条件就可以将Ci大的点与其父节点合并在一起组成一个集合。这样就可以将问题规模减小。
合并后的点(即集合)的属性如何变化呢?假如设fact[i]表示集合的Ci和,iNum[i]表示i所属集合的结点个数;那么把fact[i]/iNum[i]作为贪心原则,其值大者先合并到其父节点,最终合并成一个集合。
#include <iostream>
#include <cstring>
#include <cstdio> using namespace std; struct Edge
{
int to,next;
}e[]; int n,root,Size,Adj[],c[],num[],father[];
bool vis[]; void Init()
{
Size=;
memset(Adj,-,sizeof(Adj));
memset(vis,false,sizeof(vis));
} void Add_Edge(int u,int v)
{
///u-->v
e[Size].to=v;
e[Size].next=Adj[u];
Adj[u]=Size++;
} int Find()
{
int k=-;
double maxn=-0x3f3f3f3f;
for(int i=;i<=n;i++)
{
if(!vis[i]&&i!=root&&maxn<(double)c[i]/num[i])
{
maxn=(double)c[i]/num[i];
k=i;
}
}
return k;
} void Union(int a,int b)
{
/// a to b
num[b]+=num[a];
c[b]+=c[a];
father[a]=b;
for(int i=Adj[a];~i;i=e[i].next)
{
int v=e[i].to;
father[v]=b;
}
} int solve()
{
int ans=;
for(int i=;i<n-;i++)
{
int k=Find();
vis[k]=true;
int p=father[k];
while(vis[p]) p=father[p];
ans+=c[k]*num[p];
Union(k,p);
}
ans+=c[root];
return ans;
} int main()
{
while(scanf("%d%d",&n,&root)!=EOF)
{
if(n==&&root==) break;
Init();
for(int i=;i<=n;i++)
{
scanf("%d",c+i);
num[i]=;
}
for(int i=;i<n-;i++)
{
int u,v;
scanf("%d%d",&u,&v);
Add_Edge(u,v);
father[v]=u;
}
printf("%d\n",solve());
}
return ;
}