天天看點

Controlling Companies(DFS + 鄰接矩陣)

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      

    題意:

    給出 N,代表給出 N 條資訊。每條資訊包含i,j,p(1 <= i,j,p <= 100),代表 i 控制了 j 公司百分之 p 的股份。輸出公司之間的控制關系。

    A 公司控制 B 公司的條件為(滿足其中之一):

    1.A = B(即 A 控制了 B 百分之百的股份);

    2.A 控制了 B 超過百分之 50 的股份;

    3.A 控制了一系列的公司 ,這一系列的公司控制 B 公司股份之和超過 50,則 A 控制 B 公司。

    思路:

    DFS,鄰接矩陣儲存關系,判斷過程中記得判重即可。

    AC:

/*
TASK:concom
LANG:C++
ID:sum-g1
*/
#include<stdio.h>
#include<string.h>
int cont[105][105],val[105][105];
int vis[105],sum[105],now;

void dfs(int num)
{
    if(vis[num]) return;  //判重
    vis[num] = 1;
    for(int i = 1;i <= 100;i++)
    {
        sum[i] += val[num][i];
        if(sum[i] > 50)
        {
            cont[now][i] = 1;
            dfs(i);
        }
    }
}

int main()
{
    freopen("concom.in","r",stdin);
    freopen("concom.out","w",stdout);
    int n;
    scanf("%d",&n);
    memset(val,0,sizeof(val));
    memset(cont,0,sizeof(cont));
    while(n--)
    {
        int a,b,num;
        scanf("%d%d%d",&a,&b,&num);
        val[a][b] = num;
    }

//每次都是以一個節點向下搜尋
//vis是判重,sum是累加
    for(now = 1;now <= 100;now++)
    {
        memset(vis,0,sizeof(vis));
        memset(sum,0,sizeof(sum));
        dfs(now);
    }

    for(int i = 1;i <= 100;i++)
    {
        for(int j = 1;j <= 100;j++)
            if(i != j && cont[i][j])
            printf("%d %d\n",i,j);
    }
    return 0;
}