1.vector孩子结点表示法(原)
#include<iostream>
#include<cstdio>
#include<string.h>
#include<vector>
using namespace std;
// freopen("data.in","r",stdin);
struct Node
{
int v;
int is,no;
vector<int> son;
} a[6010];
void search(int r)
{
int s;
for(unsigned int i=0; i<a[r].son.size(); i++)
{
s=a[r].son[i];
search(s);
a[r].is+=a[s].no;
a[r].no+=max(a[s].no,a[s].is);
}
}
bool f[6010];
int main()
{
// freopen("data.in","r",stdin);
int n;
while(cin>>n)
{
memset(f,0,sizeof(f));
int son,father;
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i].v);
a[i].is=a[i].v;
a[i].no=0;
a[i].son.clear();
}
while(scanf("%d%d",&son,&father),son+father)
{
a[father].son.push_back(son);
f[son]=1;
}
for(int i=1; i<=n; i++)
{
if(!f[i])
{
search(i);
cout<<max(a[i].is,a[i].no)<<endl;
break;
}
}
}
return 0;
}
1.父兄孩子结点表示法(参考http://www.cppblog.com/notonlysuccess/archive/2009/05/11/82614.html)
在图里的邻接表(前向星)表示是一个原理,树是图的特殊情况!
#include<iostream>
#include<cstdio>
#include<string.h>
#include<vector>
using namespace std;
// freopen("data.in","r",stdin);
struct Node
{
int is,no;
int father,brother,child;
void init()
{
father=child=no=brother=0;
}
} a[6010];
void dfs(int r)
{
int child=a[r].child;
while(child)
{
dfs(child);
a[r].is+=a[child].no;
a[r].no+=max(a[child].is,a[child].no);
child=a[child].brother;
}
}
int main()
{
// freopen("data.in","r",stdin);
int n;
while(cin>>n)
{
int son,father;
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i].is);
a[i].init();
}
while(scanf("%d%d",&son,&father),son+father)
{
a[son].brother=a[father].child;
a[father].child=son;
a[son].father=father;
}
for(int i=1; i<=n; i++)
{
if(!a[i].father)
{
dfs(i);
cout<<max(a[i].is,a[i].no)<<endl;
break;
}
}
}
return 0;
}