The price of transmission of a signal from one transmitter to another or to the user is given. A price of the entire broadcast is the sum of prices of all individual signal transmissions.
Every user is ready to pay a certain amount of money to watch the match and the TV-network then decides whether or not to provide the user with the signal.
Write a program that will find the maximal number of users able to watch the match so that the TV-network's doesn't lose money from broadcasting the match.
The root of the tree is marked with the number 1, while other transmitters are numbered 2 to N-M and potential users are numbered N-M+1 to N.
The following N-M lines contain data about the transmitters in the following form:
K A1 C1 A2 C2 ... AK CK
Means that a transmitter transmits the signal to K transmitters or users, every one of them described by the pair of numbers A and C, the transmitter or user's number and the cost of transmitting the signal to them.
The last line contains the data about users, containing M integers representing respectively the price every one of them is willing to pay to watch the match.
9 6 3 2 2 3 2 9 3 2 4 2 5 2 3 6 2 7 2 8 2 4 3 3 3 1 1Sample Output
5
題意:電視臺發送信號給很多用戶,每個用戶有願意出的錢,電視臺經過的路線都有一定費用,求電視臺不損失的情況下最多給多少用戶發送信號。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define inf 10000000
#define Size 3010
using namespace std;
int read(){
int sum=0,fg=1;char c=getchar();
while(c<'0' || c>'9'){if(c=='-')fg=-1;c=getchar();}
while(c>='0' && c<='9'){sum=sum*10+c-'0';c=getchar();}
return sum*fg;
}
int be[Size],to[Size],ne[Size],w[Size],e;
void add(int x,int y,int z){to[++e]=y;ne[e]=be[x];be[x]=e;w[e]=z;}
bool p[Size];
int sum[Size];
int dp[Size][Size];
void dfs(int x){
p[x]=1;
dp[x][0]=0;
for(int i=be[x];i;i=ne[i]){
if(!p[to[i]]){
dfs(to[i]);
sum[x]+=sum[to[i]];
for(int j=sum[x];j>=0;j--){
for(int k=1;k<=sum[to[i]];k++){
dp[x][j]=max(dp[x][j],dp[x][j-k]+dp[to[i]][k]-w[i]);
}
}
}
}
}
int main(){
int n=read(),m=read();
for(int i=1;i<=n-m;i++){
int k=read();
for(int j=1;j<=k;j++){
int x=read(),w=read();
add(i,x,w);
}
}
for(int i=1;i<=n;i++)
for(int j=0;j<=m;j++)
dp[i][j]=-inf;
for(int i=n-m+1;i<=n;i++){
dp[i][1]=read();
sum[i]=1;
}
dfs(1);
for(int i=sum[1];i>=0;i--){
if(dp[1][i]>=0){
printf("%d\n",i);
break;
}
}
return 0;
}