Cow Contest
Time Limit: 1000MS | Memory Limit: 65536K | |
---|---|---|
Total Submissions: 15880 | Accepted: 8852 |
Description
N (1 ≤ N ≤ 100) cows, conveniently numbered 1..N, are participating in a programming contest. As we all know, some cows code better than others. Each cow has a certain constant skill rating that is unique among the competitors.
The contest is conducted in several head-to-head rounds, each between two cows. If cow A has a greater skill level than cow B (1 ≤ A ≤ N; 1 ≤ B ≤ N; A ≠ B), then cow A will always beat cow B.
Farmer John is trying to rank the cows by skill level. Given a list the results of M (1 ≤ M ≤ 4,500) two-cow rounds, determine the number of cows whose ranks can be precisely determined from the results. It is guaranteed that the results of the rounds will not be contradictory.
Input
* Line 1: Two space-separated integers: N and M
* Lines 2..M+1: Each line contains two space-separated integers that describe the competitors and results (the first integer, A, is the winner) of a single round of competition: A and B
Output
* Line 1: A single integer representing the number of cows whose ranks can be determined
Sample Input
5 5
4 3
4 2
3 2
1 2
2 5
Sample Output
2
Source
链接
http://poj.org/problem?id=3660
题意
n头奶牛,每头奶牛都有一个唯一的技能排名,如果奶牛A能打败奶牛B,说明A的排名比B高,具有传递性,现在给定m场比赛信息,问有多少头奶牛能确定技能排名。
题解
Floyd传递闭包。跑一遍floyd就得到了任意两头奶牛之间是否能确定关系,如果一头奶牛与其余的n-1头奶牛都能确定关系,那么它的排名就一定能确定。
代码
Status | Accepted |
---|---|
Time | 32ms |
Memory | 700kB |
Length | 1053 |
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1010;
int G[maxn][maxn];
int n, m;
void floyd() // floyd求传递闭包
{
for (int k = 1; k <= n; ++k)
{
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
{
if (G[i][k] && G[k][j]) // i->k->j
G[i][j] = 1;
}
}
}
}
int main()
{
int u, v;
while (scanf("%d%d", &n, &m) != EOF)
{
memset(G, 0, sizeof(G));
for (int i = 0; i < m; ++i)
{
scanf("%d%d", &u, &v);
G[u][v] = 1;
}
floyd();
int cnt, ans = 0;
for (int i = 1; i <= n; ++i)
{
cnt = 0;
for (int j = 1; j <= n; ++j)
{
if (G[i][j] || G[j][i]) // i和j的关系确定
cnt++;
}
if (cnt == n - 1) // 该点和别的n-1个点的关系都确定
++ans;
}
printf("%d\n", ans);
}
return 0;
}
一道大水题,了解一下floyd传递闭包。
还有一道题,HDU1704 RANK ,为啥上面的代码蜜汁超时了呢!和下面的也差不了多少。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 510;
int G[maxn][maxn];
int n, m;
void floyd() // floyd求传递闭包
{
for (int k = 1; k <= n; ++k)
{
for (int i = 1; i <= n; ++i)
{
if (G[i][k])
{
for (int j = 1; j <= n; ++j)
{
if (G[k][j]) // i->k->j
G[i][j] = 1;
}
}
}
}
}
int main()
{
int T, u, v;
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &n, &m);
memset(G, 0, sizeof(G));
for (int i = 0; i < m; ++i)
{
scanf("%d%d", &u, &v);
G[u][v] = 1;
}
floyd();
int ans = 0;
for (int i = 1; i <= n; ++i)
{
for (int j = i + 1; j <= n; ++j)
{
if (!(G[i][j] || G[j][i])) // i和j的关系不确定
ans++;
}
}
printf("%d\n", ans);
}
return 0;
}
The end.
2018-08-23 星期四