USACO2.3.5Controlling Companies

Controlling Companies

Some companies are partial owners of other companies because they have acquired part of their total shares of stock. For example, Ford owns 12% of Mazda. It is said that a company A controls company B if at least one of the following conditions is satisfied:

  • Company A = Company B
  • Company A owns more than 50% of Company B
  • Company A controls K (K >= 1) companies denoted C1, ..., CK with each company Ci owning xi% of company B and x1 + .... + xK > 50%.

Given a list of triples (i,j,p) which denote company i owning p% of company j, calculate all the pairs (h,s) in which company h controls company s. There are at most 100 companies.

Write a program to read the list of triples (i,j,p) where i, j and p are positive integers all in the range (1..100) and find all the pairs (h,s) so that company h controls company s.

PROGRAM NAME: concom

INPUT FORMAT

Line 1: n, the number of input triples to follow
Line 2..n+1: Three integers per line as a triple (i,j,p) described above.

SAMPLE INPUT (file concom.in)

3
1 2 80
2 3 80
3 1 20

OUTPUT FORMAT

List 0 or more companies that control other companies. Each line contains two integers that denote that the company whose number is the first integer controls the company whose number is the second integer. Order the lines in ascending order of the first integer (and ascending order of the second integer to break ties). Do not print that a company controls itself.

SAMPLE OUTPUT (file concom.out)

1 2
1 3
2 3
解题思路:DFS。用一个邻接矩阵f存储输入数据,f[i][j]代表i公司拥有j公司的股份。之后进行搜索,对于公司i,用一个数组path来记录公司i拥有其他公司的股份,path[j]表示公司i拥有公司j的股份多少,path[j]+=f[i][j],对于path[j]大于50的递归搜索公司j,这样就把i公司间接控制的公司的股份也计算出来了。最后判断一下path[j]是否大于50,如果是,那么i公司控制j。
View Code
 1 /*
 2 ID:spcjv51
 3 PROG:concom
 4 LANG:C
 5 */
 6 #include<stdio.h>
 7 #include<string.h>
 8 #define MAXN 100
 9 int f[105][105];
10 int visit[105],path[105];
11 int n,m;
12 void dfs(int step)
13 {
14     int i;
15     if(visit[step]) return;
16     visit[step]=1;
17     for(i=1;i<=MAXN;i++)
18     path[i]+=f[step][i];
19     for(i=1;i<=MAXN;i++)
20     if(path[i]>50&&!visit[i])
21     dfs(i);
22 }
23 int main(void)
24 {
25     freopen("concom.in","r",stdin);
26     freopen("concom.out","w",stdout);
27     int i,j,k;
28     scanf("%d",&n);
29     memset(f,0,sizeof(f));
30     while(n--)
31     {
32         scanf("%d%d%d",&i,&j,&k);
33         f[i][j]=k;
34 
35     }
36     for(i=1;i<=MAXN;i++)
37     {
38         memset(visit,0,sizeof(visit));
39         memset(path,0,sizeof(path));
40         dfs(i);
41         for(j=1;j<=MAXN;j++)
42         if(i!=j&&path[j]>50)
43         printf("%d %d\n",i,j);
44     }
45     return 0;
46 }


 
 
原文地址:https://www.cnblogs.com/zjbztianya/p/2910605.html