Banhui is a mysterious organization in SYSU, and General Mo is the president of Banhui. General Mo was dissatisfied with some of her subordinates (e.g. wenyue, JFantasy, davidmg, OYoung and Joe) last year, so she changed the hierarchical structure of Banhui. Currently, each member of Banhui may have zero, one or more than one direct boss. A is a direct subordinate of B if B is a direct boss of A. Each member may also have zero, one or more than one direct subordinate. A is a boss of B if A is direct boss of B or A has a direct subordinate who is a boss of B. If A is a boss of B, B cannot be a boss of A. Of course, A cannot be his own boss. According to General Mo’s new policy, if a member has no direct subordinate, his salary is 1; otherwise, his salary is the sum of his direct subordinates’ salaries. Now, General Mo asks you to calculate the sum of all the members’ salaries.
The input begins with a line containing an integer T (T<=200), which indicates the number of test cases. Each test case begins with a line containing an integer N (1<=N<=50), representing the number of members. The following N lines consist of an N * N matrix, where the jth element in the ith row is 1 if member i is a direct boss of member j; and 0 otherwise.
For each test case, output one line containing the sum of all the members’ salaries.
3 1 0 4 0 0 1 0 0 0 1 0 0 0 0 0 0 1 1 0 4 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0
1
5
4
As the answer may be very large, you should use long long instead of int.
#include<iostream>
#include<stdio.h>
#include<memory.h>
#include<vector>
#include<algorithm>
using namespace std;
std::vector<int > inc[202];
int matrix[202][202];
int in[202];
int salary[202];
void process(int index)
{
for (int i = 0; i < inc[index].size(); ++i)
{
/* code */
salary[inc[index][i]]+=salary[index]; //把index指向的点(boss)的工资加上直接下属的工资
in[inc[index][i]]--; //指向的那点入度减一
if(in[inc[index][i]]==0)
process(inc[index][i]);
}
}
int main(int argc, char const *argv[])
{
/* code */
int casen;
cin>>casen;
int sum;
while(casen--)
{
int num;
cin>>num;
sum=0;
for (int i = 0; i < num; ++i)
{
/* code */inc[i].clear();
in[i]=0;
salary[i]=0;
}
for (int i = 0; i < num; ++i)
{
for (int j = 0; j < num; ++j)
{
/* code */
cin>>matrix[i][j];
if(matrix[i][j]==1)
{
inc[j].push_back(i);
in[i]++;
}
}
}
for (int i = 0; i < num; ++i)
{
/* code */
if(in[i]==0)
{
if(salary[i]==0)
salary[i]=1; //同时,如果不是根,则不要初始化为1,弱爆了,检查了20多分钟
process(i); //这里注意有可能是森林
}
}
for (int i = 0; i < num; ++i)
{
/* code */
sum+=salary[i];
}
cout<<sum<<endl;
}
system("pause");
return 0;
}