題目鏈接:
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=4124
題目描述:
Median
Time Limit: 1 Second Memory Limit: 65536 KB
Recall the definition of the median of elements where is odd: sort these elements and the median is the -th largest element.
In this problem, the exact value of each element is not given, but relations between some pair of elements are given. The -th relation can be described as , which indicates that the -th element is strictly larger than the -th element.
For all , is it possible to assign values to each element so that all the relations are satisfied and the -th element is the median of the elements?
Input
There are multiple test cases. The first line of the input contains an integer , indicating the number of test cases. For each test case:
The first line contains two integers and (, ), indicating the number of elements and the number of relations. It's guaranteed that is odd.
For the following lines, the -th line contains two integers and , indicating that the -th element is strictly larger than the -th element. It guaranteed that for all , or .
It's guaranteed that the sum of of all test cases will not exceed .
Output
For each test case output one line containing one string of length . If it is possible to assign values to each element so that all the relations are satisfied and the -th element is the median, the -th character of the string should be '1', otherwise it should be '0'。
Sample Input
2 5 4 1 2 3 2 2 4 2 5 3 2 1 1 2 3
Sample Output
01000 000
Hint
For the first sample test case, as the 2nd element is smaller than the 1st and the 3rd elements and is larger than the 4th and the 5th elements, it's possible that the 2nd element is the median.
For the second sample test case, as the 1st element can't be larger than itself, it's impossible to assign values to the elements so that all the relations are satisfied.
題目描述:
T組樣例,n個數據1~n,m組關係描述這n個數的大小關係,問根據這m組關係,1~n中有哪些數可能爲中位數。
思路:
題目要求的是可能爲中位數的數,考慮如果某數不爲中位數,那麼小於它的數或者大於它的數的個數一定>=(n+1)/2,所以可以處理出所有數之間的關係矩陣,進而根據入度出度判斷;同時又因爲小於關係滿足傳遞性,所以可以用floyed閉包的方法求解矩陣。
代碼實現:
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=100+10;
int mp[maxn][maxn];
int in[maxn],out[maxn];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
mp[i][j]=0;
while(m--)
{
int u,v;
scanf("%d%d",&u,&v);
mp[u][v]=1;
}
for(int k=1; k<=n; k++)
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
mp[i][j] |=mp[i][k]&mp[k][j];
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
bool f=0;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
if(mp[i][j])
{
if(i==j)
{
f=1;
break;
}
++in[j],++out[i];
}
}
if(f)break;
}
if(f)
{
for(int i=1; i<n; ++i)printf("0");
printf("0\n");
continue;
}
for(int i=1; i<=n; i++)
{
if(in[i]>=(n+1)/2 || out[i]>=(n+1)/2)printf("0");
else printf("1");
}
printf("\n");
}
return 0;
}
遺憾!!!