----------------------------------------------------------------------------------------------------------------------------------------
贪心,类似区间不相交问题吧。就是关于题中的“不保证,H1H1:M1M1先于H2H2:M2M2。”指的是时间的开始和结束时间反了。。。。并不是23:00-1:00。。。
还有,关于输入时间,我的思路是用字符串,然后对字符串一次遍历,分别取相应的时,分,然后进行转换,得到一个分钟的数。不过很麻烦。。。。
我看了其他人的博客,才知道有scanf("%d:%d-%d:%d", &a, &b, &c, & d);这个用法。。。。。
C++代码:
#include<iostream> #include<algorithm> #include<cmath> #include<string.h> #include<string> using namespace std; const int maxn = 102; struct segment { int start; int end; }s[maxn]; bool cmp(segment a, segment b) { if (a.end == b.end) { return a.start < b.start; } return a.end < b.end; } int main() { int n; while (cin >> n) { string str; for(int j = 0; j < n; j++) { cin >> str; int hour1 = 0; int hour2 = 0; int minute1 = 0; int minute2 = 0; string hour_str1, hour_str2, minute_str1, minute_str2; hour_str1 = hour_str2 = minute_str1 = minute_str2 = ""; for (int i = 0; i < 2; i++) { hour_str1 += str[i]; } hour1 = stoi(hour_str1); for (int i = 3; i < 5; i++) { minute_str1 += str[i]; } minute1 = stoi(minute_str1); for (int i = 6; i < 8; i++) { hour_str2 += str[i]; } hour2 = stoi(hour_str2); for (int i = 9; i < 11; i++) { minute_str2 += str[i]; } minute2 = stoi(minute_str2); s[j].start = hour1 * 60 + minute1; s[j].end = hour2 * 60 + minute2; if (s[j].start > s[j].end) { //s[j].start = (hour1 - 24) * 60 + minute1; swap(s[j].start, s[j].end); } } sort(s, s + n, cmp); int sum = 1; int ans = s[0].end; for (int i = 1; i < n; i++) { if (ans < s[i].start) { sum++; ans = s[i].end; } } cout << sum << endl; } //system("pause"); return 0; }
其他大佬的代码:
链接:https://blog.csdn.net/a2459956664/article/details/51555148
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 100 + 10; struct P { int s, e; }p[maxn]; int n; int a, b, c, d; int cmp(P x, P y) { if (x.e != y.e) return x.e < y.e; else return x.s < y.s; } int main() { while (scanf("%d", &n) != EOF){ for (int i = 0; i < n; i++){ scanf("%d:%d-%d:%d", &a, &b, &c, & d); p[i].s = a * 60 + b; p[i].e = c * 60 + d; if (p[i].s > p[i].e) swap(p[i].s, p[i].e); } sort(p, p + n, cmp); int ans = 1; int temp = p[0].e; for(int i = 1; i < n; i++){ if (p[i].s > temp){ ans++; temp = p[i].e; } } printf("%d\n", ans); } return 0; }
转载于:https://www.cnblogs.com/Weixu-Liu/p/10685695.html
相关资源:JAVA上百实例源码以及开源项目