题解
[USACO16DEC] Cities and States S
1 条题解
-
0
1. 解题思路
把两个大写字母编码成0到675。读取城市时,以城市前缀和州代码为有序对,累加此前反向有序对数量,再记录当前对。
2. 坑点和注意事项
N≤2×10^5,城名≤10。前缀等于本州必须跳过,同州城市不能计入;答案可能超过int,使用long long。
3. 复杂度
- 时间复杂度:O(N+26^4)。
- 空间复杂度:O(26^4)。
/* 思路:把两个大写字母编码成0到675。读取城市时,以城市前缀和州代码为有序对,累加此前反向有序对数量,再记录当前对。 关键规则与坑点:N≤2×10^5,城名≤10。前缀等于本州必须跳过,同州城市不能计入;答案可能超过int,使用long long。 时间复杂度:O(N+26^4)。空间复杂度:O(26^4)。 */ #include <bits/stdc++.h> using namespace std; int code(string s) { return (s[0] - 'A') * 26 + s[1] - 'A'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; static long long cnt[676][676]; long long ans = 0; while (n--) { string city, state; cin >> city >> state; int a = code(city), b = code(state); if (a == b) continue; ans += cnt[b][a]; cnt[a][b]++; } cout << ans << '\n'; }
- 1