uva 10763 多种方法
2015-07-17 20:00
459 查看
题意:给出n个二元组,让你判断是否每一个二元组都存在一个与之对应的对称的二元组,且每个二元组不能和多个其他二元组相对应。
方法1:
利用map来为每个二元组计数,判断是否有map[a][b] == map[b][a]。
方法2:
也是利用了map,不过看起来更加巧妙,见代码。
方法3:
对所有的二元组按照first排序,再按照second排序,观察结果是否一样。
方法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; }
相关文章推荐
- 232——Implement Queue using Stacks(栈与队列)
- 【转】机器学习中导数最优化方法(基础篇)
- hdu 4810 Wall Painting 位操作
- SGU131--NYOJ435
- Spring AOP三种配置详细介绍
- CactiEZ中文版说明
- Linux系统防CC攻击自动拉黑IP增强版Shell脚本
- hdu 4825 Xor Sum 位操作 字典树
- Vijos P1369难解的问题
- 【asp.net】常用内置对象(Request,Response、server、Cookies)
- Physical Examination
- iOS端使用二维码扫描(ZBarSDK)和生成(libqrencode)功能
- leetcode Database3
- SVG六基本元素
- 在python中使用liblinear
- Win7系统封装制作的全过程
- 【转】LM(Levenberg-Marquard) Matlab及C语言实现
- hdu 2604 Queuing 递推/DP 矩阵快速幂 Trie数辅助
- Largest Rectangle in Histogram
- 【资源NotFoundException美元:# 0 x55字符串资源】Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x55