您的位置:首页 > 其它

Cow Contest(POJ 3660)(Floyd)(任意两点间最短路)

2016-08-23 11:28 393 查看
题目:http://acm.hust.edu.cn/vjudge/problem/12425

题意:N个选手,如果A比B强,B比C强,则A必比C强。告知若干个强弱关系,问有多少人的排名可以确定

题解:如果一个人排名已经确定,那么在他前面的人和在他后面的人的人数都应该确定,且总和为(n-1)。现在主要是求在他前面与在他后面的人有多少。Floyd算法能求出两个点之间的最短距离,也就是能求出任意两点之间的关系。那么就用Floyd算法求解这个问题。如果a比b强,那就加一条权值为1的由a到b的边。Floyd算法求出任意两个点之间的关系。如果i比j强,那么i与j之间最短距离就会被更新,就不会是INF。具体求在他前面的人和后面的人的方法看代码,代码中有注释。

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>

using namespace std;

const int INF = 1 << 10;
int dist[200][200];

int main()
{
#ifndef ONLINE_JUDGE
freopen ("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
int n, m;
scanf ("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == j) {
dist[i][j] = 0;
} else {
dist[i][j] = dist[j][i] = INF;
}
}
}
while (m--) {
int a, b;
scanf ("%d%d", &a, &b);
dist[a][b] = 1;//只加单向边,表示a在b前面
}
//Floyd算法模板
for (int k = 1; k <= n; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 1;j <= n; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
int sol = 0;
for (int i = 1; i <= n; i++) {
int cnt = 0;
for (int j = 1; j <= n; j++) {
if (i == j) continue;
if (dist[i][j] != INF) {//比i弱的++
cnt++;
}
if (dist[j][i] != INF) {//比i强的++
cnt++;
}
}
if (cnt == n - 1) {//如果比i强与弱的总人数等于n-1,则i的排名确定
sol++;
}
}
printf ("%d\n", sol);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: