离散题目17
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
给出集合X和X上的关系R,求关系R在X上的对称闭包s(R)。
例如:
X={1,2,3,4,5} , R={<1,1>,<2,1>,<3,3>,<2,3>,<3,2>,<4,5>}
s(R)= {<1,1>,<1,2>,<2,1>,<2,3>,<3,2>,<3,3>,<4,5>,<5,4>}
Input
多组输入,每组输入第一行为集合X的元素;第二行为一个整数n ( n > 0 ),代表X上的关系R中序偶的个数;接下来n行用来描述X上的关系R,每行两个数字,表示关系R中的一个序偶。细节参考示例输入。
非空集合X的元素个数不大于500,每个元素的绝对值不大于2^32 - 1。
Output
每组输入对应一行输出,为X上关系R的对称闭包s(R),s(R)中的序偶根据序偶中的第一个值升序排列,如果第一个值相同则根据第二个值升序排列;具体输出格式见样例(注意:样例每个逗号后有一个空格)。
Example Input
1 2 3 4 5 6 1 1 2 1 3 3 2 3 3 2 4 5
Example Output
[(1, 1), (1, 2), (2, 1), (2, 3), (3, 2), (3, 2), (3, 3), (4, 5), (5, 4)]
Hint
Author
1、注意输出格式
2、此题又与书上不同,看示例输出便知道,它是将每一个x,y不同时的序偶,全部取对称,再做排序,输出
3、注意输出格式
以下为TLE代码
以下为AC代码
#include <bits/stdc++.h>
using namespace std;
set<int> s;
string dd;
struct node
{
int x;
int y;
} q[10000];
bool INPUT()//此处超时
{
string cc;
getline(cin,cc);
stringstream ss(cc);
int t;
s.clear();
while(ss>>t)
{
s.insert(t);
}
return true;
}
int cmp(node a, node b)
{
if(a.x == b.x)
return a.y < b.y;
else
return a.x < b.x;
}
int main()
{
int n;
while(INPUT())//循环输入时超时
{
int flag = 0;
cin>>n;
for(int i = 0; i < n; i++)
{
cin>>q[i].x>>q[i].y;
if(q[i].x != q[i].y)
{
q[n+flag].x = q[i].y;
q[n+flag].y = q[i].x;
flag++;
}
}
sort(q,q+n+flag,cmp);
cout<<"[";
for(int i = 0; i < n+flag; i++)
{
if(i != 0)
cout<<", ";
cout<<"("<<q[i].x<<", "<<q[i].y<<")";
}
cout<<"]"<<endl;
memset(q,0,sizeof(q));
getline(cin,dd);
}
return 0;
}
/***************************************************
Result: Time Limit Exceeded
Take time: 1010ms
Take Memory: 0KB
Submit time: 2017-05-17 21:55:43
****************************************************/
#include <bits/stdc++.h>
using namespace std;
//set<int> s;
string dd;
struct node
{
int x;
int y;
} q[10000];
/*bool INPUT()
{
string cc;
getline(cin,cc);
stringstream ss(cc);
int t;
s.clear();
while(ss>>t)
{
s.insert(t);
}
return true;
}*/
int cmp(node a, node b)
{
if(a.x == b.x)
return a.y < b.y;
else
return a.x < b.x;
}
int main()
{
int n;
string cc;
while(getline(cin,cc))//因为考虑到输入集合元素时,对操作无影响,所以果断直接水过;
{
int flag = 0;
cin>>n;
for(int i = 0; i < n; i++)
{
cin>>q[i].x>>q[i].y;
if(q[i].x != q[i].y)
{
q[n+flag].x = q[i].y;
q[n+flag].y = q[i].x;
flag++;
}
}
sort(q,q+n+flag,cmp);
cout<<"[";
for(int i = 0; i < n+flag; i++)
{
if(i != 0)
cout<<", ";
cout<<"("<<q[i].x<<", "<<q[i].y<<")";
}
cout<<"]"<<endl;
memset(q,0,sizeof(q));
getline(cin,dd);
}
return 0;
}
/***************************************************
User name
Result: Accepted
Take time: 40ms
****************************************************/