您的位置:首页 > 其它

uva 10763 多种方法

2015-07-17 20:00 459 查看
题意:给出n个二元组,让你判断是否每一个二元组都存在一个与之对应的对称的二元组,且每个二元组不能和多个其他二元组相对应。

方法1:

利用map来为每个二元组计数,判断是否有map[a][b] == map[b][a]。

#include <iostream>
#include <cstdio>
#include <map>
using namespace std;

typedef pair<int, int> pii;
map<pii, int> mp;
map<pii, int>::iterator it;

int main ()
{
int n;
while ( scanf("%d", &n), n )
{
mp.clear();
for ( int i = 0; i < n; i++ )
{
int a, b;
scanf("%d%d", &a, &b);
mp[make_pair( a, b )]++;
}
bool flag = true;
for ( it = mp.begin(); it != mp.end(); it++ )
{
int a = (*it).first.first, b = (*it).first.second;
pii p1 = make_pair( a, b ), p2 = make_pair( b, a );
if ( mp[p1] == mp[p2] )
{
mp.erase(p1);
mp.erase(p2);
}
else
{
flag = false;
break;
}
}
if ( flag ) printf("YES\n");
else printf("NO\n");
}
return 0;
}


方法2:

也是利用了map,不过看起来更加巧妙,见代码。

#include <iostream>
#include <cstdio>
#include <map>
using namespace std;

typedef pair<int, int> pii;
map<pii, int> mp;
map<pii, int>::iterator it;

int main ()
{
int n;
while ( scanf("%d", &n), n )
{
mp.clear();
for ( int i = 0; i < n; i++ )
{
int a, b;
scanf("%d%d", &a, &b);
mp[make_pair( a, b )]++;
mp[make_pair( b, a )]--;
}
bool flag = true;
for ( it = mp.begin(); it != mp.end(); it++ )
{
if ( (*it).second != 0 )
{
flag = false;
break;
}
}
if ( flag ) printf("YES\n");
else printf("NO\n");
}
return 0;
}


方法3:

对所有的二元组按照first排序,再按照second排序,观察结果是否一样。

#include <algorithm>
#include <cstdio>
using namespace std;

const int N = 500000;

struct Node
{
int first;
int second;
} node1
, node2
;

bool cmp1( Node x, Node y )
{
if ( x.first != y.first )
return x.first < y.first;
return x.second < y.second;
}

bool cmp2( Node x, Node y )
{
if ( x.second != y.second )
return x.second < y.second;
return x.first < y.first;
}

int main ()
{
int n;
while ( scanf("%d", &n), n )
{
for ( int i = 0; i < n; i++ )
{
int a, b;
scanf("%d%d", &a, &b);
node1[i].first = a, node1[i].second = b;
node2[i].first = a, node2[i].second = b;
}
sort( node1, node1 + n, cmp1 );
sort( node2, node2 + n, cmp2 );
bool flag = true;
for ( int i = 0; i < n; i++ )
{
if ( node1[i].first != node2[i].second
|| node1[i].second != node2[i].first )
{
flag = false;
break;
}
}
if ( flag ) printf("YES\n");
else printf("NO\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: