UVA 11748 Rigging Elections 【dfs】

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2848
题意:n个人选举,给出m个人的投票人对于每个人的优先级,想让第c个人赢,问能不能

思路:对于两个人上场,如果a能赢b,就建一条a->b的边,然后问题其实就变成能否以c为根节点是一棵树,直接dfs一遍即可

代码:

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <queue>
#include <math.h>
#include <map>
#include <string>

using namespace std;

int n, m, c;

vector<int> g[110];
int is[110][110];
int vis[110];
int ans;

void dfs(int u)
{
    if (!vis[u]) ans += 1;
    vis[u] = 1;
    for (int i = 0; i < g[u].size(); i++)
        if (!vis[g[u][i]]) dfs(g[u][i]);
}

int main()
{
    while (cin >> n >> m >> c)
    {
        if (n == 0 && m == 0 && c == 0) break;
        memset(is,0,sizeof(is));
        memset(vis, 0, sizeof(vis));
        for (int i = 0; i <= 105; i++) g[i].clear();

        for (int i = 1; i <= m; i++)
        {
            for (int j = 1; j <= n; j++)
            {
                int x;
                cin >> x;
                is[i][x] = j;
            }
        }

        for (int i = 1; i <= n; i++)
            for (int j = i + 1; j <= n; j++)
            {
                int num = 0;
                for (int k = 1; k <= m; k++)
                {
                    if (is[k][i] < is[k][j])
                        num++;
                }
                if (num * 2 > m)
                    g[i].push_back(j);
                else
                    g[j].push_back(i);
            }
        ans = 0;
        dfs(c);
        if (ans == n) puts("yes");
        else puts("no");
    }
    return 0;
}

你可能感兴趣的:(DFS,uva)